简体   繁体   中英

Google Maps API v3: Add Polylines inside a loop?

I'm in the process of migrating our Map application from V2 to V3 (3.2). I had a loop that read LatLng and put them in a array to display as a Polyline on the map. I then set the length of my array to 0 and then fill it again in the loop with other LatLng to display another Polyline... and so on (many times).

It was working fine in V2, but not in V3. Since my code is complex, I tried to write the simpliest code possible to demonstrate my issue:

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

What happens is that only the second Polyline is shown (and not the first one). To make it works, I have to either use a different variable name (points1, points2, points3, ...) which I can't use because my code is normally in a loop or re-declare my variable each time in the loop instead of before it (var points=[] before each Polyline and remove the points.length=0 line).

Maybe I'm missing something about JavaScript, but I usually declare my variable outside the loop (before) once and use it inside the loop.

What am I doing wrong? Can someone help?

Here's a simple Map I did to demonstrate my issue:
http://www.canamgroup.ws/GM.nsf/Map?OpenPage
(It's not in a loop, but the issue is the same. Only the last Polyline is displayed if I don't use a different variable name for my array or if I don't re-declare it each time)

Thanks!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM