سؤال

I'm using the Google Maps v3 API to generate a group of locations for a given city. I want the map to load centered at the average position of all locations. To do this, I'm loading LatLng objects of all the locations I want to mark on the map into an array called locations and using the following code:

if(locations.length > 1)
{
   var  bounds = new google.maps.LatLngBounds(locations[0], locations[1]);
   for(var x = 2; x < locations.length; x++) bounds.extend(locations[x]);
   var center = bounds.getCenter();
}
else var center = locations[0];

However, in testing, I used this code to define the locations array:

var locations = [];
locations.push(new google.maps.LatLng(50.11658, 8.68552));
locations.push(new google.maps.LatLng(50.10026, 8.66941));
locations.push(new google.maps.LatLng(50.10989, 8.68822));
locations.push(new google.maps.LatLng(50.11074, 8.68269));
locations.push(new google.maps.LatLng(50.1040552, 8.6936269));
locations.push(new google.maps.LatLng(50.110206, 8.6818686));
locations.push(new google.maps.LatLng(50.10957, 8.69077));

and got a crazy result for center. If I remove the first location (the one at 50.11658, 8.68552), the code works. If I move it so that it's not the first location pushed into the array, the code works. I have no idea why or how that location would or could produce this error!

هل كانت مفيدة؟

المحلول

I believe the problem is the constructor for LatLngBounds expects the first position to be the South West bounding point and the second to the be the North East bounding point. It looks like your points are in the wrong order.

The arguments are optional, so the following should work:

if(locations.length > 1) {
   var bounds = new google.maps.LatLngBounds();
   for(var x = 0; x < locations.length; x++) 
       bounds.extend(locations[x]);
   var center = bounds.getCenter();
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top