我在谷歌地图v3上有多个标记。当地图加载时,它会绘制所有标记和折线。折线的初始路径与每个标记的LatLng相同。拖动标记时,应将原始LatLng之间的线绘制到标记的新位置。您可以移动地图上的所有和/或任何标记,每个标记应该有单独的行,显示标记的原始LatLng到新位置。我在下面的代码中做了类似的事情,但问题是当我移动标记时它会丢失标记的前一行。它始终只显示拖动标记的一行。如何解决这个问题呢。提前谢谢...... Ash
<!DOCTYPE html>
<html>
<head>
<title>Marker with line example two</title>
<style type="text/css">
html {
height: 100%;
}
body {
height: 100%;
margin: 0;
padding: 0;
}
#map_canvas {
height: 100%;
}
</style>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="Scripts/jquery-1.10.2.min.js"></script>
<script>
var line;
var myLatlng = new google.maps.LatLng(41.7833, 5.2167);
var marker;
var lines = [];
function initialize() {
var domain = [new google.maps.LatLng(11.2583, 75.1374)];
var markers = [];
var mapOptions = {
zoom: 2,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
opacity: 0.2,
disableDefaultUI: true,
draggable: false
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var lineCoordinates = [
new google.maps.LatLng(53.215556, 56.949219),
new google.maps.LatLng(75.797201, 125.003906),
new google.maps.LatLng(37.7833, 144.9667),
new google.maps.LatLng(-24.797201, 26.003906),
new google.maps.LatLng(27.797201, -101.003906)
];
for (i = 0; i < lineCoordinates.length; i++) {
var latLng = lineCoordinates[i],
marker = new google.maps.Marker({
position: latLng,
draggable: true,
title: i.toString(),
map: map,
});
markers.push({
key: i.toString(),
latLng: latLng
});
line = new google.maps.Polyline({
path: [latLng, latLng],
strokeOpacity: 0.8,
strokeWeight: 2,
strokeColor: '#f00',
geodesic: true
});
line.setMap(map);
lines.push(line);
google.maps.event.addListener(marker, 'drag', function (event) {
var title = this.title,
result = $.grep(markers, function (e) { return e.key === title }),
oldLatLng = result[0].latLng,
newLatLng = new google.maps.LatLng(this.getPosition().lat(), this.getPosition().lng());
line.setPath([oldLatLng, newLatLng]);
});
} //end of for loop
} //end of initialize function
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width: 1000px; height: 675px; margin-left: 400px; margin-top: 38px;"></div>
</body>
</html>
答案 0 :(得分:1)
你快到了。您必须为事件侦听器的变量line
进行闭包:
(function(line) {
google.maps.event.addListener(marker, 'drag', function (event) {
var title = this.title,
result = $.grep(markers, function (e) { return e.key === title }),
oldLatLng = result[0].latLng,
newLatLng = new google.maps.LatLng(this.getPosition().lat(), this.getPosition().lng());
line.setPath([oldLatLng, newLatLng]);
});
})(line);