resizing a google map to fit a group of markers

限于喜欢 提交于 2020-04-05 19:15:36

问题


I'm using the V3 version of google maps, and wondered how to go about this-- I have an array of google.maps.Markers with their LatLng positions set.

I would like to loop through the array and find the min/max latitude and longitude values of the markers, and center and resize the map so all the markers fit on the screen, with a small fudge factor.

Looping through the markers array I can handle, but I'm not sure of how go about centering and resizing the map to fit them all (with a small border region surrounding, so no markers are flush against an edge.)

I'm not sure if this helps or matters but the <div> the map lives in is 320x200 pixels.


回答1:


You can create a function like

function setBounds() {

    var bounds = new google.maps.LatLngBounds();
    for (var i=0; i < markersArray.length; i++) {
        bounds.extend(markersArray[i].getPosition());
    }
    map.fitBounds(bounds);
}

As simple as that!




回答2:


See the google.maps.Map fitBounds method

Add all the positions of your markers to an empty google.maps.LatLngBounds object, then call fitBounds on it.

var bounds = new google.maps.LatLngBounds();
for (var i=0; i < yourArrayOfMarkers.length; i++) {
   bounds.extend(yourArrayOfMarkers[i].getPosition();
}
yourMap.fitBounds(bounds);


来源:https://stackoverflow.com/questions/16331430/resizing-a-google-map-to-fit-a-group-of-markers

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