我有以下代码用于标记世界地图中的几个点,当点击每个点时,随机选择两个点并从该选定点创建折线到随机两个点。
var markerBounds = new google.maps.LatLngBounds();
var locations = [
['Rio De Janeiro (GIG)', -22.808903,-43.243647, 5],
['Sydney (SYD)', -33.946111,151.177222, 4],
['Delhi (DEL)', 28.5665,77.103088, 5],
['Tokyo (TYO)', 35.689444,139.691667, 3],
['New York (JFK)', 40.639751,-73.778925, 2],
['Frankfurt (FRA)', 50.026421,8.543125, 1]
];
var flightPlanCoordinates1 = [];
var flightPlanCoordinates2 = [];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 1,
minZoom:1,
center: new google.maps.LatLng(0, 0),
mapTypeId: google.maps.MapTypeId.TERRAIN
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
var p1 = Math.floor(Math.random() * 6);
var p2 = Math.floor(Math.random() * 6);
Point1 = new google.maps.LatLng(this.position.lat(),this.position.lng());
Point2 = new google.maps.LatLng(locations[p1][1], locations[p1][2]);
Point3 = new google.maps.LatLng(locations[p2][1], locations[p2][2]);
flightPlanCoordinates1.push(Point1);
flightPlanCoordinates1.push(Point2);
flightPlanCoordinates2.push(Point1);
flightPlanCoordinates2.push(Point3);
var flightPath1 = new google.maps.Polyline({
path: flightPlanCoordinates1,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
var flightPath2 = new google.maps.Polyline({
path: flightPlanCoordinates2,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath1.setMap(map);
flightPath2.setMap(map);
}
})(marker, i));
}
点击新点后,我需要删除以前的折线。
任何帮助都会表示赞赏。
答案 0 :(得分:2)
将两个局部折线变量flightPath1
和flightPath2
设为全局,然后在标记点击处理程序的开头重置其map
属性。
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
if (flightPath1!== null) {
flightPath1.setMap(null);
}
if (flightPath2!== null) {
flightPath2.setMap(null);
}
...
在旁边节点上,您已将全局坐标数组flightPlanCoordinates1
和flightPlanCoordinates2
声明为全局,但您并未在标记点击处理程序中重置其内容。相反,您需要在每次标记点击时为数组添加越来越多的坐标。为避免这种情况,您应该将数组转换为局部变量。
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
...
var flightPlanCoordinates1 = [Point1, Point2];
var flightPlanCoordinates2 = [Point1, Point3];
...
工作示例:JSFiddle
答案 1 :(得分:1)
以下是来自Google Maps API v3的精确example。
您需要在函数中使用此代码:
flightPath1.setMap(null);
flightPath2.setMap(null);