谷歌地图API v3如何将地图居中于标记

21
我正在寻找一种方法,在地图上的标记点超出可视区域时重新居中(聚焦)地图。例如,如果您单击不在视野范围内的标记点...
Marker 1: 纽约 Marker 2: 旧金山
在V2中,我是这样做的...但对于v3,containsLatLng 需要额外的库并且对我没有起作用...(请参见我的其他帖子:Google Maps v3 map.getBounds().containsLatLng is not a function)有没有其他方法可以聚焦到标记点的位置?
更新:
        if ((!map.getBounds().contains(marker.getPosition())) & (showAllCategoryElements == 0)) {
        var newCenterPointLng = (map.getBounds().getCenter().lng() + marker.getPosition().lng()) / 2;
        var newCenterPointLat = (map.getBounds().getCenter().lat() + marker.getPosition().lat()) / 2;

        map.panTo(marker.getPosition());
        //map.setCenter(new google.maps.LatLng(newCenterPointLat, newCenterPointLng));

        if (!map.getBounds().contains(marker.getPosition())){
            map.zoomOut();
        } 
    }

你是在询问适用于版本3还是版本2的代码吗?你同时拥有标签和版本2的代码。 - Andrew Leach
2个回答

53

你需要使用的方法是contains(),而不是containsLatLng()。 map.getBounds().contains(marker.getPosition())

你可以使用setCenter()或panTo()方法将地图居中于标记位置:map.setCenter(marker.getPosition())map.panTo(marker.getPosition())

所以如果我理解你想做什么的话,代码应该是这样的:

if ((!map.getBounds().contains(marker.getPosition())) && (showAllCategoryElements == 0)) { //Note the double &  
    map.setCenter(marker.getPosition());  
    //OR map.panTo(marker.getPosition());  
}

有了你的提示,我已经更改了它(请参见我的帖子顶部)...如果我使用“PanTo”,则不需要“map.setCenter”吗?现在我在“http://maps.gstatic.com/cat_js/intl/de_de/mapfiles/api-3/9/2/%7Bmain,geometry%7D.js file”中遇到了“a未定义”的问题。 - Jim
以上代码已更新。如果您继续遇到错误,可能需要发布更多的代码。 - puckhead

0

其实并不是很复杂,只是有点棘手。

在创建标记的点击事件时,您可以获取您声明的经度和纬度以使点位,并将地图视角移动到该位置。

在我的代码中,经度和纬度被声明为从HTML获取的变量:

    var longitude = item.querySelector('#longitude').innerText;
    var latitude = item.querySelector('#latitude').innerText;

    const marker = new google.maps.Marker({
            title: titel,
            icon: "[url to marker]",
            position: new google.maps.LatLng(longitude, latitude),
            map: map
        });

然后根据经度和纬度进行定位。

        google.maps.event.addListener(marker, "click", function() {
            // JQuery to close all other markers before opening this one
            jQuery(".gm-ui-hover-effect").click();

            // Pan to long lat defined inside the marker locations
            var laLatLng = new google.maps.LatLng(longitude, latitude);
            map.panTo(laLatLng);
            map.setZoom([place value for zoom level here]);


            infowindow.open(map, this);
        });

        infowindow.close();

注意:在我的代码中,这是通过for循环来获取所有标记位置的,对于大多数代码来说这并不重要,但如果您直接复制粘贴此代码,则值得注意。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接