javascript 显示信息窗口后防止谷歌地图移动

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18404948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:47:37  来源:igfitidea点击:

Preventing Google Maps Move After Displaying Infowindow

javascriptgoogle-mapsgoogle-maps-api-3infowindow

提问by Burak Erdem

I'm trying to display a infowindow on a Google Maps. It displays perfect, when you hover over a marker it loads up a infowindow but the map jumps to fit in the window. I don't want the map to move but rather infowindow set its position according to map. Booking.com has something like this.

我正在尝试在 Google 地图上显示信息窗口。它显示完美,当您将鼠标悬停在标记上时,它会加载一个信息窗口,但地图会跳转以适应窗口。我不希望地图移动,而是希望 infowindow 根据地图设置其位置。Booking.com 有类似的东西。

EDIT:Added my code

编辑:添加我的代码

Here is the stripped down version of my code. I'm getting all the info from an AJAX serviceand this service returns response(which holds some more info too).

这是我的代码的精简版本。我从AJAX 服务获取所有信息,该服务返回response(它也包含更多信息)。

$.ajax({
    url: 'URL',
    dataType: "json",
    type: "GET",
    success: function(response) {
        // delete all markers
        clearOverlays();

        var infowindow = new google.maps.InfoWindow();

        for (var i = 0; i < response.length; i++) {
            item = response[i];

            var marker = new google.maps.Marker({
                position: new google.maps.LatLng(item.lat, item.lng),
                map: map,
                url: item.detail_url
            });

            markersArray.push(marker);

            // display infowindow
            google.maps.event.addListener(marker, "mouseover", (function(marker, item) {
                return function() {
                    infowindow.setOptions({
                        content: 'SOME CONTENT HERE FOR INFOWINDOW'
                    });

                    infowindow.open(map, marker);
                }
            })(marker, item));

            // remove infowindow
            google.maps.event.addListener(marker, 'mouseout', function() {
                infowindow.close();
            });

            // marker click
            google.maps.event.addListener(marker, 'click', function() {
                window.location.href = marker.url;
            });
        }
    }
});

As you can see below, the first image shows the infowindow displayed at bottom of marker while second one shows the infowindow displayed on top of the marker. The map doesn't move but infowindow sets its position within the boundries of the map.

正如您在下面看到的,第一张图像显示了标记底部显示的信息窗口,而第二张图像显示了标记顶部显示的信息窗口。地图不会移动,但信息窗口将其位置设置在地图边界内。

Infowindow bottom of markerInfowindow on top of marker

标记的信息窗口底部Infowindow on top of marker

回答by Suvi Vignarajah

In your declaration for setting the info window options infowindow.setOptions, add the following option to disable the panning of the map when the infowindow is displayed, disableAutoPan : true.

在设置信息窗口选项的声明中infowindow.setOptions,添加以下选项以在显示信息窗口时禁用地图平移disableAutoPan : true

However this will also mean you'll need to calculate the real estate you have available to display the infowindow on your map and give it a position using the positionoption. Otherwise it won't be guaranteed that your infowindow will be completely visible on the map.

但是,这也意味着您需要计算可用于在地图上显示信息窗口的空间,并使用该position选项为其指定位置。否则无法保证您的信息窗口在地图上完全可见。

https://developers.google.com/maps/documentation/javascript/reference#InfoWindowOptions

https://developers.google.com/maps/documentation/javascript/reference#InfoWindowOptions

EDIT: How to calculate screen real estate

编辑:如何计算屏幕空间

I realize I was pretty vague with my suggestion to calculate the screen real estate available to set the position of your infowindow, when part of your question was to actually set the infowindow's position. So I've provided an update to my answer on how you can calculate the screen real estate and adjust your infowindow's position.

我意识到我对计算可用于设置信息窗口位置的屏幕空间的建议非常含糊,而您的问题的一部分是实际设置信息窗口的位置。因此,我提供了有关如何计算屏幕空间和调整信息窗口位置的答案的更新。

The key is to first convert your points from LatLng to pixels, and find out the pixel coordinate of the marker on the map with relation to the pixel coordinate of the map's center. The following snippet demonstrates how this can be done.

关键是首先将您的点从 LatLng 转换为像素,并找出地图上标记的像素坐标与地图中心像素坐标的关系。以下代码段演示了如何做到这一点。

getPixelFromLatLng: function (latLng) {
    var projection = this.map.getProjection();
    //refer to the google.maps.Projection object in the Maps API reference
    var point = projection.fromLatLngToPoint(latLng);
    return point;
}

Once you've got your pixel coordinates, you'll need to find out which quadrant of the map canvas the marker is currently residing in. This is achieved by comparing the X and Y coordinates of the marker to the map, like so:

获得像素坐标后,您需要找出标记当前位于地图画布的哪个象限。 这是通过将标记的 X 和 Y 坐标与地图进行比较来实现的,如下所示:

quadrant += (point.y > center.y) ? "b" : "t";
quadrant += (point.x < center.x) ? "l" : "r";

Here, I'm determining if the point is in the bottom right, bottom left, top right or top left quadrant of the map based on it's relative position to the map's center. Keep in mind this is why we use pixels as opposed to LatLng values, because LatLng values will always yield the same result - but reality is the marker can be in any quadrant of the map canvas depending on panning.

在这里,我根据点与地图中心的相对位置来确定该点是否位于地图的右下角、左下角、右上角或左上角象限。请记住,这就是我们使用像素而不是 LatLng 值的原因,因为 LatLng 值将始终产生相同的结果 - 但实际情况是标记可以位于地图画布的任何象限中,具体取决于平移。

Once you know which quadrant the marker is in, you can give offset values to the infowindow to position it so it's visible on the map - like so:

一旦您知道标记位于哪个象限,您就可以为信息窗口提供偏移值以定位它,使其在地图上可见 - 如下所示:

if (quadrant == "tr") {
    offset = new google.maps.Size(-70, 185);
} else if (quadrant == "tl") {
    offset = new google.maps.Size(70, 185);
} else if (quadrant == "br") {
    offset = new google.maps.Size(-70, 20);
} else if (quadrant == "bl") {
    offset = new google.maps.Size(70, 20);
}
//these values are subject to change based on map canvas size, infowindow size

Once the offset value is determined you can just adjust the pixelOffsetof your infowindow on whatever listener you have invoking the infoWindow.open()method. This is done by using the setOptions()method for infowindows:

一旦确定了偏移值,您就可以pixelOffset在调用该infoWindow.open()方法的任何侦听器上调整信息窗口的。这是通过使用setOptions()infowindows的方法完成的:

infowindow.setOptions({pixelOffset : self.getInfowindowOffset(self.map, marker)}); 

Here is a working JSFiddle exampleof the solution described above.

这是上述解决方案的一个有效JSFiddle 示例

Note:You will notice the annoying "arrow" on the infowindow displaying desbite the position of your infowindow, this is part of the default Google Map's setting for infowindows and I could not find a proper way of getting rid of it. There was a suggestion here, but I couldn't get it to work. Alternatively you can use the infobox libraryor the infobubble library- which gives you more styling options.

注意:您会注意到信息窗口上令人讨厌的“箭头”显示您的信息窗口的位置,这是信息窗口的默认 Google 地图设置的一部分,我找不到摆脱它的正确方法。有人建议在这里,但我无法得到它的工作。或者,您可以使用infoboxinfobubble 库- 它为您提供更多样式选项。

回答by mgPePe

Suvi Vignarajah's answer is great, what I didn't like about it was how unpredictable the position of the window is near the edges.

Suvi Vignarajah 的回答很棒,我不喜欢的是窗户靠近边缘的位置是多么不可预测。

I tweaked it so that the bubble glues to the wall as it should be expected: http://jsfiddle.net/z5NaG/5/

我调整了它,使气泡像预期的那样粘在墙上:http: //jsfiddle.net/z5NaG/5/

The only condition is that you need to know the width& heightof the infoWindow, you can position it quite nicely. You would work it out through the maps' pixels. If you don't know it you could initialize the InfoWindow offscreen, get it's size and proceed opening it again at the right spot. Ugly but would work.

唯一的条件是你需要知道infoWindow的width& height,你可以很好地定位它。你可以通过地图的像素来解决它。如果您不知道它,您可以在屏幕外初始化 InfoWindow,获取它的大小并在正确的位置再次打开它。丑,但会工作。

First initialize on overlay at time of map initialization by running this function:

首先通过运行此函数在地图初始化时在叠加层上进行初始化:

    ourOverlay:null,
    createOverlay:function(){
        this.ourOverlay = new google.maps.OverlayView();
        this.ourOverlay.draw = function() {};
        this.ourOverlay.setMap(this.map);
    },

Then at openevent adjust the offset like so:

然后在open事件中像这样调整偏移量:

getInfowindowOffset: function (map, marker) {
    // Settings
    var iwWidth = 240; // InfoWindow width 
    var iwHeight = 190; // InfoWindow Height
    var xOffset = 0;
    var yOffset = 0;

    // Our point of interest
    var location = this.ourOverlay.getProjection().fromLatLngToContainerPixel(marker.getPosition()); 

    // Get Edges of map in pixels: Sout West corner and North East corner
    var swp = this.ourOverlay.getProjection().fromLatLngToContainerPixel(map.getBounds().getSouthWest()); 
    var nep = this.ourOverlay.getProjection().fromLatLngToContainerPixel(map.getBounds().getNorthEast()); 

    // Horizontal Adjustment
    if(location.x<iwWidth/2){
        xOffset= iwWidth/2-location.x;
    }else if(location.x>nep.x-iwWidth/2){
        xOffset = (nep.x-iwWidth/2)-location.x ;
    }

    // Vertical Adjustment
    if(location.y<iwHeight){
        yOffset = location.y + iwHeight-(location.y-nep.y);
    }

    // Return it
    return new google.maps.Size(xOffset, yOffset);

},

And the result is pretty nice, but this triangle seems out of place now.

结果非常好,但这个三角形现在似乎不合适。

You can use InfoBoxto remove the pointy arrow on bottom:

您可以使用InfoBox删除底部的尖箭头:

            GmapsManager.infowindow = new InfoBox({
            content:'',
            alignBottom: true,
            closeBoxURL: "",
        });

and style the bubble with the following code:

并使用以下代码设置气泡样式:

.infobox-popup{
    background: #fff;
    -webkit-border-radius: 3px;
    border-radius: 3px;
    padding: 5px;
    margin-left: -100px;
    margin-bottom: 30px;
    width: 200px;
    -webkit-box-shadow: 0 0 1px 0 #595959;
    box-shadow: 0 0 1px 0 #595959;
}