[英]Google Maps API v3: Add Polylines inside a loop?
我正在將Map應用程序從V2遷移到V3(3.2)。 我有一個循環,它讀取LatLng並將其放入數組中,以在地圖上顯示為折線。 然后,將數組的長度設置為0,然后在循環中再次用其他LatLng填充它,以顯示另一個Polyline ...,依此類推(多次)。
在V2中運行正常,但在V3中運行不正常。 由於我的代碼很復雜,因此我嘗試編寫盡可能簡單的代碼來演示我的問題:
function setPolyline(points) {
var polyline = new google.maps.Polyline({
path: points,
strokeColor: '#FF0000',
strokeOpacity: 0.5,
strokeWeight: 2
});
polyline.setMap(map);
}
var mapDiv = document.getElementById('map');
var mapCenter = new google.maps.LatLng(0,0);
var mapOptions = {
zoom: 2,
center: mapCenter,
backgroundColor: '#E1E1E1',
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(mapDiv, mapOptions);
var points=[];
points[0]=new google.maps.LatLng(-35, 71);
points[1]=new google.maps.LatLng(-36, 75);
points[2]=new google.maps.LatLng(-37, 91);
setPolyline(points);
points.length=0;
points[0]=new google.maps.LatLng(-31, 71);
points[1]=new google.maps.LatLng(-32, 75);
setPolyline(points);
發生的是僅顯示第二條折線(而不顯示第一條折線)。 為了使其正常工作,我必須使用一個不能使用的變量名(points1,points2,points3等),因為我的代碼通常在循環中,或者每次在循環中都要重新聲明我的變量而不是之前(每個多段線之前的var points = []並刪除points.length = 0行)。
也許我缺少關於JavaScript的知識,但通常我會在循環之前(之前)聲明一次變量,然后在循環內使用它。
我究竟做錯了什么? 有人可以幫忙嗎?
這是我用來演示問題的簡單地圖:
http://www.canamgroup.ws/GM.nsf/Map?OpenPage
(它不是循環的,但是問題是相同的。如果我沒有為數組使用不同的變量名,或者每次都沒有重新聲明它,則僅顯示最后一條折線)
謝謝!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.