Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Maps API: Calculate Center/Zoom of Polyline

I have an overlay that is dynamically generated from user data, so I need to know how to find the center of that overlay.

Currently, I am just using the first coordinates from the overlay, but that really does not represent the center of the overlay. Therefore when I load the map, it is not centered on the overlay.

Does anyone have a good method for centering the map on the overlay, by calculating the center, not hard coding it?

var latlng = new google.maps.LatLng(38.269239, -122.276010);     var myOptions = {         zoom: 15,//Calculate this somehow?         center: latlng,// Calculate value from array of coordinates?         mapTypeId: google.maps.MapTypeId.HYBRID     }; 
like image 967
Nic Hubbard Avatar asked Jul 23 '10 17:07

Nic Hubbard


People also ask

How do I calculate the area of a polygon in Google Maps?

Right-click on the map at your starting point and choose the Measure distance option. Add points around the location's boundary. Once you close the shape by clicking on the starting point, the Google Maps area calculator will automatically process the area of your shape.

How do I check the zoom level on Google Maps?

You can change the zoom level of the map using simple steps. Step 1 Go to Add or Edit Map page . Step 2 Select 'Default zoom level' in the 'Map Information section'. Step 3 click save map and see the changes.

How do I zoom in Google Maps API?

Users can zoom the map by clicking the zoom controls. They can also zoom and pan by using two-finger movements on the map for touchscreen devices.


2 Answers

If you have a list of coordinates, you can loop over them and add them to a LatLngBounds object. Here is a example for the V3 API, but the concept in V2 is similar:

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

After that, you can get the center with:

bounds.getCenter(); 

Or alternatively, you can call map.fitBounds() directly, which will center the map around the center of the bounds and adjust the zoom, so that the whole bounds will fit exactly into the view port.

map.fitBounds(bounds); 
like image 169
tux21b Avatar answered Oct 05 '22 18:10

tux21b


Based on @tux21b,

      var bounds = new google.maps.LatLngBounds();       polyline.getPath().forEach(function(e){//can't do polyline.getPath()[i] because it's a MVCArray           bounds.extend(e);       })                _map.fitBounds(bounds); 
like image 31
Anderson Avatar answered Oct 05 '22 19:10

Anderson