0

我正在使用 Google Maps v3 API 为给定城市生成一组位置。我希望地图以所有位置的平均位置为中心加载。为此,我将要在地图上标记的所有位置的 LatLng 对象加载到一个名为的数组locations中,并使用以下代码:

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];

但是,在测试中,我使用此代码来定义位置数组:

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));

并得到了一个疯狂的结果center。如果我删除第一个位置(位于 50.11658、8.68552 的位置),则代码有效。如果我移动它使其不是推入数组的第一个位置,则代码有效。我不知道该位置为什么或如何产生此错误!

4

1 回答 1

0

我认为问题在于 LatLngBounds 的构造函数期望第一个位置是西南边界点,第二个位置是东北边界点。看来您的积分顺序错误。

参数是可选的,因此以下应该有效:

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();
}
于 2010-12-11T04:17:13.413 回答