从谷歌地图中删除现有多段线

Remove existing polylines from google map

本文关键字:段线 删除 谷歌地图      更新时间:2023-09-26

我有以下代码用于标记世界地图中的几个点,当单击每个点时,随机选择两个点,并创建从该选定点到随机两点的多段线。

http://jsfiddle.net/sux7eo3d/

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));
}

单击新点后,我需要删除以前的多段线。

任何帮助都将不胜感激。

使两个局部多段线变量flightPath1flightPath2全局化,然后在标记单击处理程序开始时重置它们的map属性。

google.maps.event.addListener(marker, 'click', (function(marker, i) {    
  return function() {
    if (flightPath1!== null) {
      flightPath1.setMap(null);
    }
    if (flightPath2!== null) {
      flightPath2.setMap(null);
    }
    ...

在侧节点上,您已经将坐标数组flightPlanCoordinates1flightPlanCoordinates2声明为全局,但没有在标记单击处理程序中重置它们的内容。相反,每次单击标记都会向阵列添加越来越多的坐标。为了避免这种情况,您应该将数组转换为局部变量。

google.maps.event.addListener(marker, 'click', (function(marker, i) {
  return function() {
    ...
    var flightPlanCoordinates1 = [Point1, Point2];
    var flightPlanCoordinates2 = [Point1, Point3];
    ...

工作示例:JSFiddle

下面是Google Maps API v3的一个确切示例。

你需要在你的功能中使用这个代码:

flightPath1.setMap(null);
flightPath2.setMap(null);