在调用另一个JSON之前删除Leaflet映射中的所有数据/标记

时间:2014-06-20 01:57:50

标签: json leaflet

我正在检索不同的数据,以使用不同的JSON文件标记传单地图。每个单选按钮都会检索不同的JSON文件。但是,当我选择不同的单选按钮时,我无法清除标记。所有标记只是从一个JSON文件添加到另一个。我希望能够在选择不同的单选按钮时清除所有标记。

我四处搜索并阅读了map.removeLayer(MyLayer);将删除所有标记。所以我创建了一系列标记,称为"标记"并放置在一个名为" markersLayer"的图层中。当我尝试删除" markersLayer"时,它并没有在地图上留下一个标记。现在没有绘制任何内容,而不是清除不同JSON文件中的先前标记。

我只想使用我使用单选按钮选择的特定JSON文件中的数据来显示这些标记。

HTML:

<div style="text-align: center;">
    <h1 id="title">Map Visualization 3</h1>
    <label><input type="radio" class="location" name="location" value="locations1" checked="checked">Location Set 1</label>
    <label><input type="radio" class="location" name="location" value="locations2">Location Set 2</label>
    <label><input type="radio" class="location" name="location" value="locations3">Location Set 3</label>
<ul id="location-list"></ul>
    <div id="map" style="width: 80%; max-width: 900px; height: 600px; margin: 0 auto;"></div>
</div>

JS:

var map;
var markers = [];
var markersLayer;
var updateMap = function() {
    var uri = $('input.location:checked').val() + '.json';
    $.getJSON(uri, function(response){
        $('ul#location-list').empty();


        var locationCoor = []; 
        var marker;

        for(var i=0; i < response.length; i++){

            var lat = response[i].latitude;
            var lon = response[i].longitude;
            $('ul#location-list').append('<li>(' + lat + ', ' + lon + ')</li>');
            //console.log(lat, lon);
            locationCoor[i] = [lat, lon];
            //console.log(locationCoor);

            var popup = L.popup()
                .setLatLng([lat, lon])
                .setContent('<h3 style="margin:0 0 3px 0;"><a href="' + response[i].link + '">' + response[i].title + '</a></h3><img width="180px" height="auto" src="' + response[i].imageUrl + '">');

            marker = L.marker([lat, lon], {
                clickable: true
            }).bindPopup(popup, {showOnMouseOver:true});

            markers[i] = marker; 
            console.log(markers);
        }

        markersLayer = L.layerGroup(markers);
        markersLayer.addTo(map);



        var bounds = new L.latLngBounds(locationCoor);
        map.fitBounds(bounds, {padding: [50,50]});
        markers.length = 0;
    });
};

$(document).ready(function(){
    map = L.map('map');
    L.tileLayer('https://{s}.tiles.mapbox.com/v3/examples.map-i87786ca/{z}/{x}/{y}.png', {
        maxZoom: 18,
        id: 'examples.map-20v6611k'
    }).addTo(map);

    $('input.location').on('change', updateMap);
    updateMap();
});

JSON 1:

[
  {
    "title": "Weathertop",
    "link": "http://en.wikipedia.org/wiki/Weathertop",
    "latitude": 38.80,
    "longitude": -77.12,
    "imageUrl": "assets/img/location-images/Weathertop.jpg"
  },
{
  "title": "Rivendell",
  "link": "http://lotr.wikia.com/wiki/Rivendell",
  "latitude": 38.78,
  "longitude": -77.18,
  "imageUrl": "assets/img/location-images/Rivendell2.jpg"
},
{
  "title": "Minas Tirith",
  "link": "http://lotr.wikia.com/wiki/Minas_Tirith",
  "latitude": 38.76,
  "longitude": -77.18,
  "imageUrl": "assets/img/location-images/320px-Minas_Tirith.jpg"
}

]

JSON2:

[
  {
    "title": "Chicago",
    "link": "http://en.wikipedia.org/wiki/Weathertop",
    "latitude": 41.836,
    "longitude": -87.604980,
    "imageUrl": "assets/img/location-images/Weathertop.jpg"
  },
{
  "title": "Detroit",
  "link": "http://lotr.wikia.com/wiki/Rivendell",
  "latitude": 42.326062,
  "longitude": -83.078613,
  "imageUrl": "assets/img/location-images/Rivendell2.jpg"
},
{
  "title": "Indianopolis",
  "link": "http://lotr.wikia.com/wiki/Minas_Tirith",
  "latitude": 39.741,
  "longitude": -86.154785,
  "imageUrl": "assets/img/location-images/320px-Minas_Tirith.jpg"
}

]

3 个答案:

答案 0 :(得分:14)

您不应该重新创建markersLayer对象。你想要的是创建一次,然后继续添加/删除标记。

在您在文件顶部定义markersLayer的行中,您现在还想将其定义为L.LayerGroup。我们不会重新创建此对象。

如果要更新地图,则会清除markersLayer中的所有现有标记。这是通过调用markersLayer.clearLayers()来完成的。这不会从地图中删除markersLayer。它只会删除此图层包含的标记。

从此图层移除所有标记后,您现在可以自由地向markersLayer添加新图层。

您的代码如下所示:

var map;
var markers = [];
var markersLayer = new L.LayerGroup(); // NOTE: Layer is created here!
var updateMap = function() {
  // NOTE: The first thing we do here is clear the markers from the layer.
  markersLayer.clearLayers();

  var uri = $('input.location:checked').val() + '.json';
  $.getJSON(uri, function(response){
    $('ul#location-list').empty();


    var locationCoor = []; 
    var marker;

    for(var i=0; i < response.length; i++){

        var lat = response[i].latitude;
        var lon = response[i].longitude;
        $('ul#location-list').append('<li>(' + lat + ', ' + lon + ')</li>');
        //console.log(lat, lon);
        locationCoor[i] = [lat, lon];
        //console.log(locationCoor);

        var popup = L.popup()
            .setLatLng([lat, lon])
            .setContent('<h3 style="margin:0 0 3px 0;"><a href="' + response[i].link + '">' + response[i].title + '</a></h3><img width="180px" height="auto" src="' + response[i].imageUrl + '">');

        marker = L.marker([lat, lon], {
            clickable: true
        }).bindPopup(popup, {showOnMouseOver:true});

        markersLayer.addLayer(marker); 
        console.log(markers);
    }

    // NOTE: We are no longer recreating the layer here. Remove these lines of code.
    //markersLayer = L.layerGroup(markers);
    //markersLayer.addTo(map);




    var bounds = new L.latLngBounds(locationCoor);
    map.fitBounds(bounds, {padding: [50,50]});
    markers.length = 0;
});
};

$(document).ready(function(){
map = L.map('map');
L.tileLayer('https://{s}.tiles.mapbox.com/v3/examples.map-i87786ca/{z}/{x}/{y}.png', {
    maxZoom: 18,
    id: 'examples.map-20v6611k'
}).addTo(map);

// NOTE: We add the markersLayer to the map here. This way, the layer is only added once.  
markersLayer.addTo(map);

$('input.location').on('change', updateMap);
updateMap();
});

答案 1 :(得分:3)

参考Removing leaflet layers and L.marker method

基本概念:您可以在单独的图层上添加标记(即var markers = new L.FeatureGroup();),然后在地图上添加该图层,而不是直接在地图上添加所有标记({} {1}})在循环之外。

JSFiddle

答案 2 :(得分:0)

对于我来说,它可以正常工作:

$(“。leaflet-marker-icon”)。remove();

$(“。leaflet-popup”)。remove();