我认为问题与如何为多段线构建路径数组有关,但必须有这样的方法。目标是从名为"address[]"的数组输入字段创建一个Geocode位置数组。我已经通过这样做让多段线工作:
// ARRAY
var linePath = [
new google.maps.LatLng(37.772323, -122.214897),
new google.maps.LatLng(21.291982, -157.821856),
new google.maps.LatLng(-18.142599, 178.431),
new google.maps.LatLng(-27.46758, 153.027892)
];
// console.log(linePath);
[P { Ia=37.772323, Ja=-122.21489700000001}, P { Ia=21.291982, Ja=-157.82185600000003}, P { Ia=-18.142599, Ja=178.43100000000004}, P { Ia=-27.46758, Ja=153.02789200000007}]
但是,当我尝试从$.each语句创建一个数组时,该数组会以不同的方式出现,并且不起作用。这是我写的代码:
// ARRAY
$("input[name='submit']").click(function() {
var geocoder = new google.maps.Geocoder();
locations = new Array();
$("input[name='address[]']").each(function() {
geocoder.geocode({"address" : this.value }, function(results) {
var addrLl = results[0].geometry.location;
locations.push(addrLl);
var marker = new google.maps.Marker({
map: map,
position: addrLl
});
});
});
var connect = new google.maps.Polyline({
path: locations,
strokeColor: "#FF0000",
strokeOpacity: 1.
});
connect.setMap(map);
return false;
});
// console.log(locations);
[]
[+] 0 P { Ia=41.8843266, Ja=-78.79295300000001}
[+] 1 P { Ia=35.9614504, Ja=-79.04755590000002}
有什么想法吗?
地理编码是异步的-在构建多段线时,您的结果可能尚未返回,因此不会包含在多段线中。当地理编码器返回时(可能在一秒钟后),点将被添加到位置,因此当控制台记录阵列时,您会看到它,但多段线不会知道它。
幸运的是,Maps API有一个巧妙的解决方案,那就是使用MVCArray。替换:
locations = new Array();
带有
locations = new MVCArray();
现在,每次向阵列中添加新点时,即使是在创建多边形之后,也会通知多边形并更新以包含该点。