簡體   English   中英

如何清除傳單地圖上的所有路徑和標記?

[英]how to clear all paths and markers on a leaflet map?

我添加了一個clear_btn ,我想從標記和路徑中清除地圖。

function onClearBtn_clicked() {
    map.removeLayer(markers)
    markers.clearLayers()
    markers = []
}

但是,不會從地圖中刪除任何內容。

您將如何重構此代碼以使其實現?

var map;

$(function() {
  loadMap()
  setCallbacks()

});

var markers = [];
//var lines = [];



var finishIcon = L.icon({
  iconUrl: 'js/images/finish_icon.ico',
  //    shadowUrl: 'leaf-shadow.png',

  iconSize: [30, 30], // size of the icon
  shadowSize: [12, 12], // size of the shadow
  iconAnchor: [3, 30], // point of the icon which will correspond to marker's location
  shadowAnchor: [4, 62], // the same for the shadow
  popupAnchor: [-3, -76] // point from which the popup should open relative to the iconAnchor
});


function onMap_clicked(e) {
  var markerLocation = e.latlng;
  var selectedRadio = $('input:radio[name=marker]:checked').val();


  if (markers[selectedRadio]) {
    map.removeLayer(markers[selectedRadio])
  }

  if (selectedRadio == 1) {
    markers[selectedRadio] = L.marker(markerLocation, {
      className: selectedRadio,
      icon: finishIcon
    }).addTo(map);

  } else if (selectedRadio == 0) {
    markers[selectedRadio] = L.marker(markerLocation, {
      className: selectedRadio
    }).addTo(map)
  };

  $("#marker_" + selectedRadio).val(markerLocation.lng + ", " + markerLocation.lat);
}


function onCompareBtn_clicked() {
  var lat0 = markers[0]._latlng.lat;
  var lng0 = markers[0]._latlng.lng;

  var lat1 = markers[1]._latlng.lat;
  var lng1 = markers[1]._latlng.lng;

  var url = "https://www.==?zoom=17&lat=" + lat0 + "&lon=" + lng0 + "&from_lat=" + lat0 + "&from_lon=" + lng0 + "&to_lat=" + lat1 + "&to_lon=" + lng1 + "&at_req=0&at_text=Now";
  var beta_url = url + "&rp_id=beta";

  parseRoutingResponse(exampleResponse1, "prod")
  parseRoutingResponse(exampleResponse1, "beta")
}


function onClearBtn_clicked() {
    map.removeLayer(markers)
    markers.clearLayers()
    markers = []
}

function parseRoutingResponse(data, type) {
  var alternatives = data.alternatives;
  for (i = 0; i < alternatives.length; i++) {
    var lines[i] = {
      type: "LineString",
      stroke : "true",
      properties: {
        type: type,
        alt_id: i
      },
      coordinates: []
    };
    results = data.alternatives[i].response.results;
    for (j = 0; j < results.length; j++) {
      lines[i].coordinates[j] = [
        results[j].path.x,
        results[j].path.y
      ];
    }
  }

  loadMapLayer(lines);
}


function setCallbacks() {
  setCompareCallback();
  setClearCallback();
  setDddCallback();
}


function setClearCallback() {
map.on('click', onMap_clicked);
  $("#clear_btn").click(onClearBtn_clicked);
}

function setCompareCallback() {
map.on('click', onMap_clicked);
  $("#compare_btn").click(onCompareBtn_clicked);
}

function setDddCallback() {
  $('select[name="dropdown"]').change(function() {
    //        var item = this.selectedIndex;
    var value = this.value;
    geojson.eachLayer(function(layer) {
      try {
        if (layer.feature.geometry.properties.alt_id == value) {
          highlightFeature({
            "target": layer
          })
        } else {
          resetHighlight({
            "target": layer
          })
        }
      } catch (e) {}
    });
  });
}


function loadMapLayer(lines) {
  geojson = L.geoJson(lines, {
    style: regularStyle
  }).addTo(map);
}


//========= on map load
function loadMap() {
  map = L.map('map').setView([51.505, -0.09], 13);
  var tileLayer = L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
    attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors,<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
    maxZoom: 18,
    id: 'mapbox.streets',
    accessToken: 'pk.eyJ1IjoiZWxhZG===J9.3HqHQ4BMRvSPaYe8ToA7YQ'
  }).addTo(map);
}

var beta_highlightedStyle = {
  "color": "green",
  "weight": 5,
  "opacity": 0.65,
  "dashArray": "true"
}


var beta_regularStyle = {
  "color": "red",
  "weight": 5,
  "opacity": 0.65
}


var prod_highlightedStyle = {
  "color": "purple",
  "weight": 5,
  "opacity": 0.65,
  "dashArray": "true"
}


var prod_regularStyle = {
  "color": "blue",
  "weight": 5,
  "opacity": 0.65
}


function highlightFeature(layer) {
  layer.target.setStyle(prod_highlightedStyle);
  if (!L.Browser.ie && !L.Browser.opera) {
    layer.bringToFront();
  }
}

function resetHighlight(layer) {
  geojson.resetStyle(layer.target);
  layer.setStyle(prod_regularStyle);
}


function onEachFeature(feature, layer) {
  layer.on({
    mouseover: highlightFeature,
    mouseout: resetHighlight,
    // click: zoomToFeature
  });
}
var markers = [];
markers.clearLayers()

您將markers聲明為Array ,但隨后將其用作L.LayerGroup

確定要使用的兩個接口之一,並始終使用它。 單獨添加層以在地圖上,然后使用一個Array ,以保持它們的跟蹤,或添加L.LayerGroup ,然后添加層以/移除層從L.LayerGroup 但是不要兩者混用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM