Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

resizing a google map to fit a group of markers

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.

like image 421
larryq Avatar asked May 02 '13 06:05

larryq


People also ask

How many markers can Google Maps handle?

2048 characters in URL is just under 100 GeoCode values. So, again no more than 100 markers.

How do I move a marker smoothly on Google Maps?

The initialize() function creates a Google Map with a marker. The transition() and moveMarker() are used to move marker smoothly on click on the Google map.


2 Answers

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!

like image 77
MrUpsidown Avatar answered Sep 18 '22 01:09

MrUpsidown


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);
like image 41
geocodezip Avatar answered Sep 18 '22 01:09

geocodezip