【问题标题】:Google Maps API v3 - fitBounds centers only one markerGoogle Maps API v3 - fitBounds 仅居中一个标记
【发布时间】:2012-07-01 03:51:34
【问题描述】:

我有几个要检索的标记,并希望将地图居中。 是的,我已经阅读了所有其他答案,但它似乎对我不起作用: 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);
        }
}

【问题讨论】:

    标签: javascript google-maps google-maps-api-3 bounds


    【解决方案1】:

    您的代码总是调用 fitBounds,其 LatLngBounds 只有一个点,即最后一个标记... 如果您多次调用该函数,则每次调用它时,都会拟合最后一个标记的边界。 您可以在 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 被初始化一次,并随着每个新的标记进行扩展。

    【讨论】:

    • 是的,我也这么认为,并且我尝试在那里定义markerBounds(以及您可以放置​​它的所有其他可能的位置)。但是我再次尝试了你的方式,但仍然像你说的那样只将最后一个居中..
    • 嗯,这很奇怪..如果它位于一个只有在它应该工作时才执行的地方。您发布的代码上方是什么?
    • 啊,我找到了,我确实在它上面有一个“function codeAddress(row) {”。现在我已经在该函数之外设置了 markerBounds 并且它可以工作! :)
    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2013-02-24
      • 2011-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-27
      • 1970-01-01
      • 2013-04-11
      • 2013-11-05
      相关资源
      最近更新 更多