2010-12-11 107 views
0

我正在使用Google Maps v3 API为给定城市生成一组位置。我希望地图以所有位置的平均位置为中心。要做到这一点,我加载所有我想在地图上标记为被称为locations和使用下面的代码的阵列位置的经纬度对象:Google Maps API绑定错误

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),则代码有效。如果我移动它,以便它不是推入数组的第一个位置,则代码有效。我不知道为什么或如何地点会或可能产生这个错误!

回答

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