Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
37
rated 0 times [  39] [ 2]  / answers: 1 / hits: 22777  / 14 Years ago, thu, december 30, 2010, 12:00:00

So I checked previous questions regarding this, which all relate to V2, which is of no help.



So, I create two markers, save them in an array as markers[to] and markers[from]



And then add them with this



function route(){
for(var key in markers) {
flightPlanCoordinates.push(markers[key].position);
}
flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
strokeColor: #FF0000,
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
}


Brilliant.
But. Next time I use it (With new markers in the array) it just adds a polyline there without removing the previous one.
I seem to have tried everything, removing from the first array, the flightPath, setMap(null) and so forth.



What's the correct way to remove the previous line before drawing a new one?



EDIT: SOLVED
Solution



function route(){
var flightPlanCoordinates = [];
for(var key in markers) {
flightPlanCoordinates.push(markers[key].position);
}
if(flightPath) {
flightPath.setPath(flightPlanCoordinates);
} else {
flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
strokeColor: #FF0000,
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
}
}


Reason:
flightPlanCoordinates needs to be initialized within the scope, this resets the array every time it is used, cleaning it out properly. (Also thanks for the input below to make the code a bit nicer.


More From » google-maps

 Answers
21

I don't see var before flightPath = new..., so I presume flightPath is a global variable.



function route(){
//flightPath.setMap(null); Doesnt't work!?
for(var key in markers) {
flightPlanCoordinates.push(markers[key].position);
}
if(flightPath) {//If flightPath is already defined (already a polyline)
flightPath.setPath(flightPlanCoordinates);
} else {
flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
strokeColor: #FF0000,
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);//It's not necessary to setMap every time
}

}

[#94438] Tuesday, December 28, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
freddiejarretk

Total Points: 612
Total Questions: 103
Total Answers: 88

Location: Armenia
Member since Sat, Dec 31, 2022
1 Year ago
;