在调用另一个JSON之前删除Leaflet映射中的所有数据/标记 [英] Removing all data/markers in Leaflet map before calling another JSON

查看:163
本文介绍了在调用另一个JSON之前删除Leaflet映射中的所有数据/标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm retrieving different data to mark leaflet map using different JSON files. Each radio button retrieves a different JSON file. However, I'm having trouble clearing the markers when I select different radio button. All the markers just adds up from one JSON file to another. I want to be able to clear all the markers when I select a different radio button.

我到处搜索并阅读了该地图.将删除所有标记.因此,我创建了一个称为"markers"的标记数组,并将其放置在一个名为"markersLayer"的层中.当我尝试删除"markersLayer"时,它没有在地图上留下单个标记.现在无需从其他JSON文件中清除以前的标记,而不会绘制任何内容.

I searched around and read that map.removeLayer(MyLayer); will remove all markers. So I created an array of markers called "markers" and placed in a layer called "markersLayer". When I tried removing "markersLayer", it didn't leave a single marker on the map. Instead of clearing previous markers from different JSON file, now nothing is plotted.

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

I only want to show those markers using data from the specific JSON file that I selected using radio button.

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"
}

]

推荐答案

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

You should not be re-creating the markersLayer object. What you want is to create it once, and then continue to add/remove markers from it.

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

In your line where you define the markersLayer at the top of the file, you now also want to define it here as an L.LayerGroup. We will not be re-creating this object.

要更新地图时,将清除markersLayer中的所有现有标记.这可以通过调用markersLayer.clearLayers()来完成.这不会从地图上删除markersLayer.它只会删除该图层包含的标记.

When you want to update the map, you will clear all the existing markers from the markersLayer. This is accomplished by calling markersLayer.clearLayers(). This will not remove the markersLayer from the map. It will only remove the markers this layer contains.

一旦所有标记都已从该层中删除,您现在就可以将新层添加到markersLayer中了.

Once all of the markers have been removed from this layer, you are now free to add new layers to 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();
});

这篇关于在调用另一个JSON之前删除Leaflet映射中的所有数据/标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆