views:

73

answers:

2

Using the latest version of google maps. How to add markers using longitute and latitude and automatically adjust the zoom level of the map to include all the markers using javascript.

+2  A: 

You add markers to your google map by instantiating a marker object for each of your latitude/longitude pairs:

var marker = new google.maps.Marker({
    position: currentLatLng, 
    map: map,
    title:"Title!"
}); 

The map option on the marker constructer will associate the new market object with your map.

To zoom your map to include your new markers, you use the fitBounds method on the map object. fitBounds takes a latLngBounds object as a parameter. This object has a handy extend method which will adjust the bounds to include a new latitude/longitude. So you just need to spin through all your points, calling extend on a single latLngBounds object. This will extend the bounds to include all your markers. Once you have done this, you pass this object into the fitBounds method on the map and it will zoom to show all your new markers.

Cannonade
+1  A: 

See it this helps:

Zoom-To-Fit All Markers, Polylines or Polygons on A Google Map

The article targets API v2. For v3, there is a native function called Map.fitBounds().

Salman A