Google Maps API v3 - fitBounds centers only one marker

女生的网名这么多〃 提交于 2019-12-11 11:42:50

问题


I have a few markers that I retrieve and want to center the map to. Yes, I have read all the other answers, but it doesn't seem to work for me: 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);
        }
}

回答1:


Your code is always calling fitBounds with a LatLngBounds of only one point, the last marker... If you are calling that function several times, each time you call it, will fitBounds of the last marker. You could define the markerBounds variable outside the geocoder.geocode function, so it will retain it's value.

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);
        }
}

Now, markerBounds is initialized once, and extended with each new marker.




回答2:


Actually, you can ouput the what coords are store in your bounds to log by:

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

And then just check your log in console of Chrome. You will know the problem, cuz I found it there's two duplicate coords in my bounds and then target the problem.



来源:https://stackoverflow.com/questions/11264762/google-maps-api-v3-fitbounds-centers-only-one-marker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!