I have a sample google map here where I can draw a polyline and drag the marker to redraw the polyline. When I'm dragging the marker, I'm usingPath.setMap(null)
to redraw the Polyline as,
google.maps.event.addListener(marker, 'dragend', function(event) {
var newLatLng = event.latLng;
var index = Latlngs.map(function(element) {
return element[0];
}).indexOf(marker.id);
if (index !== -1) {
Latlngs[index] = [marker.id, newLatLng];
}
console.log(Latlngs);
var changedLine=[];
for (var i = 0; i < Latlngs.length; i++) {
changedLine.push(Latlngs[i][1]);
}
console.log(changedLine);
Path.setMap(null);
draw(changedLine, map);
});
But the polyline is not clearing as required. How can I clear old path and redraw the same?
The issue is the creation of the markers.
When you create a new Marker you call draw
without removing the existing Polyline
(Path
)
This would fix it:
function placeMarkerAndPanTo(latLng, map) {
var marker = new google.maps.Marker({
position: latLng,
map: map,
draggable: true
});
markers.push(marker);
marker.id = uniqueId;
Latlngs.push([uniqueId, latLng]);
uniqueId++;
console.log(Latlngs);
//draw(Line, map);
google.maps.event.addListener(marker, 'dragend', function(event) {
if(Path)Path.setMap(null);
var newLatLng = event.latLng;
var index = Latlngs.map(function(element) {
return element[0];
}).indexOf(marker.id);
if (index !== -1) {
Latlngs[index] = [marker.id, newLatLng];
}
var changedLine=[];
for (var i = 0; i < Latlngs.length; i++) {
changedLine.push(Latlngs[i][1]);
}
draw(changedLine, map);
});
google.maps.event.trigger(marker,'dragend',
{latLng:marker.getPosition()})
}
But there is no need to draw a new Polyline, polylines-pathes may be modified directly:
function initMap() {
var goo = google.maps,
map = new goo.Map(document.getElementById('map'), {
zoom: 10,
center: new goo.LatLng(12.8799313333, 77.5991386667)
}),
line = new goo.Polyline({
path:[],
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2 ,
map:map
}),
markers = new goo.MVCArray;
goo.event.addListener(map, 'click', function(e) {
var marker = new goo.Marker({ position:e.latLng,
map:map,
draggable:true});
markers.push(marker);
//push new point to the path
line.getPath().push(marker.getPosition());
goo.event.addListener(marker,'dragend',function(){
//simply update the path
line.getPath().setAt(markers.indexOf(this),
this.getPosition());
});
goo.event.addListener(marker,'dblclick',function(){
//remove marker and path-point
line.getPath().removeAt(markers.indexOf(this));
markers.removeAt(markers.indexOf(this));
this.setMap(null)
});
});
}
html,body,#map{height:100%;margin:0;padding:0;}
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?v=3&callback=initMap"></script>