我有一个示例谷歌地图here,我可以绘制折线并拖动标记重绘折线。当我拖动标记时,我使用Path.setMap(null)
重新绘制折线,
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);
});
但折线未按要求清除。我怎样才能清除旧路径并重绘它?
答案 0 :(得分:2)
问题在于标记的创建。
当您创建新标记时,请致电draw
而不删除现有Polyline
(Path
)
这会解决它:
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()})
}
但是不需要绘制新的折线,折线 - pathes可以直接修改:
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)
});
});
}
&#13;
html,body,#map{height:100%;margin:0;padding:0;}
&#13;
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?v=3&callback=initMap"></script>
&#13;