1

我有一些我要检索并希望将地图居中的标记。是的,我已经阅读了所有其他答案,但它似乎对我不起作用: Google Map API v3 — set bounds and center

JS:

geocoder.geocode( {'address': loc}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var markerBounds = new google.maps.LatLngBounds();
            var coordinate = results[0].geometry.location;
            var icon = new google.maps.MarkerImage("images/icon-"+type+".png", new google.maps.Size(37, 44));   

            //create the marker
            var marker = new google.maps.Marker({
                map: map, 
                position: coordinate,
                visible: true,
                id: type,
                shadow: shadow,
                icon: icon
            });
            markerBounds.extend(coordinate);
            map.fitBounds(markerBounds);
        }
}
4

2 回答 2

1

您的代码总是使用只有一个点的 LatLngBounds 调用 fitBounds,最后一个标记...如果您多次调用该函数,每次调用它时,都会 fitBounds 最后一个标记。您可以在 geocoder.geocode 函数之外定义 markerBounds 变量,因此它将保留它的值。

var markerBounds = new google.maps.LatLngBounds();
geocoder.geocode( {'address': loc}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var coordinate = results[0].geometry.location;
            var icon = new google.maps.MarkerImage("images/icon-"+type+".png", new google.maps.Size(37, 44));   

            //create the marker
            var marker = new google.maps.Marker({
                map: map, 
                position: coordinate,
                visible: true,
                id: type,
                shadow: shadow,
                icon: icon
            });
            markerBounds.extend(coordinate);
            map.fitBounds(markerBounds);
        }
}

现在,markerBounds 被初始化一次,并随着每个新的标记进行扩展。

于 2012-06-29T15:49:35.017 回答
0

实际上,您可以通过以下方式输出存储在边界中的坐标:

console.log("mapFitBounds:"+bounds);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

然后只需检查您的 Chrome 登录控制台。你会知道这个问题,因为我发现它有两个重复的坐标在我的范围内,然后定位问题。

于 2016-02-07T05:51:42.187 回答