如何在Leaflet地图上添加开关标记的按钮?

4

我遇到了一个问题,需要添加删除地图上的标记功能。我阅读并尝试了很多不同的代码,但我不知道如何删除特定类型的所有标记。我的代码是这样的:

var map_var =L.map('map_id').setView([45.4642700,  9.1895100], 16);

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map_var);

sidebar = L.control.sidebar('helpsidebar', { position: 'right' });
sidebar.addTo(map);

Button1 = new L.Control.Button(L.DomUtil.get('bike'), { toggleButton: 'active' });
Button1.addTo(map);
Button1.on('click', function () {
    if (bike.isToggled()) {
        sidebar.hide(
        for(i=0;i<marker_bike.length;i++) {
            map.removeLayer(marker_bike[i]);
            } );
    } else {
        sidebar.show(marker_bike.addTo(map_var))
    }
});

var bike = $.getJSON( "./static/bike_coordinate.json", function(json1) {
           for (var i = 0; i < json1.length; i++) {
            var place = json1[i];
            console.log( place );
               // Creating a marker and putting it on the map
            var customIcon = L.icon({
            iconUrl: './static/bike_share.png',
            iconSize:     [38, 40], // size of the icon
            iconAnchor:   [10, 40], // point of the icon which will correspond to marker's location
            popupAnchor:  [5, -40] // point from which the popup should open relative to the iconAnchor
            }); 
            var marker_bike = L.marker(place.coordinate, {icon: customIcon});
            if (marker_bike != null){
                marker_array.push(marker_bike);
                marker_bike.addTo(map_var).bindPopup(place.Indirizzo);
                } else{$('#bike').text = "Error"}
            }

    });


    var ferrovia = $.getJSON( "./static/train.json", function(json2) {
           for (var i = 0; i < json2.length; i++) {
            var place = json2[i];
            console.log( place );
               // Creating a marker and putting it on the map
            var customIcon = L.icon({
            iconUrl: './static/train.png',
            iconSize:     [38, 40], // size of the icon
            iconAnchor:   [10, 40], // point of the icon which will correspond to marker's location
            popupAnchor:  [5, -40] // point from which the popup should open relative to the iconAnchor
            }); 
            var marker_train = L.marker(place.coordinate, {icon: customIcon});
            if (marker_train != null){
                marker_array.push(marker_train);
                marker_train.addTo(map_var).bindPopup(place.Indirizzo);
                }
            else{$('#ferrovia').text = "Error"}
            }

    });

当我编写按钮的代码时,所有地图都会消失。 我想添加一个按钮,让用户点击并显示或隐藏特定类型的标记(因此有3个按钮)。
编辑:我也尝试了这段代码,但它不起作用:
var map_var =L.map('map_id').setView([45.4642700,  9.1895100], 16);
console.log('a')
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map_var);

var group1 = L.featureGroup();
var group2 = L.featureGroup();
var group3 = L.featureGroup();

var bike = $.getJSON( "./static/bike_coordinate.json", function(json1) {
           for (var i = 0; i < json1.length; i++) {
            var place = json1[i];
            console.log( place );
               // Creating a marker and putting it on the map
            var customIcon = L.icon({
            iconUrl: './static/bike_share.png',
            iconSize:     [38, 40], // size of the icon
            iconAnchor:   [10, 40], // point of the icon which will correspond to marker's location
            popupAnchor:  [5, -40] // point from which the popup should open relative to the iconAnchor
            }); 
            var marker_bike = L.marker(place.coordinate, {icon: customIcon});
            if (marker_bike != null){
                //marker_array.push(marker_bike);
                marker_bike.addTo(group1).bindPopup(place.Indirizzo);
                } else{$('#bike').text = "Error"}
            }

    });

    var ferrovia = $.getJSON( "./static/train.json", function(json2) {
           for (var i = 0; i < json2.length; i++) {
            var place = json2[i];
            console.log( place );
               // Creating a marker and putting it on the map
            var customIcon = L.icon({
            iconUrl: './static/train.png',
            iconSize:     [38, 40], // size of the icon
            iconAnchor:   [10, 40], // point of the icon which will correspond to marker's location
            popupAnchor:  [5, -40] // point from which the popup should open relative to the iconAnchor
            }); 
            var marker_train = L.marker(place.coordinate, {icon: customIcon});
            if (marker_train != null){
                //marker_array.push(marker_train);
                marker_train.addTo(group2).bindPopup(place.Indirizzo);
                }
            else{$('#ferrovia').text = "Error"}
            }

    });

var farmacie = $.getJSON( "./static/farmacie.json", function(json3) {
       for (var i = 0; i < json3.length; i++) {
        var place = json3[i];
        console.log( place );
           // Creating a marker and putting it on the map
        var customIcon = L.icon({
        iconUrl: './static/phar.png',
        iconSize:     [35, 37], // size of the icon
        iconAnchor:   [10, 40], // point of the icon which will correspond to marker's location
        popupAnchor:  [5, -40] // point from which the popup should open relative to the iconAnchor
        }); 
        var marker_pha = L.marker(place.coordinate, {icon: customIcon});
        if (marker_pha != null){
            //marker_array.push(marker_pha);
            marker_pha.addTo(group3).bindPopup('FARMACIA '+place.Indirizzo);
            }
        else{$('#farmacie').text = "Error"}
        }

});

map_var.addLayer(group1);
map_var.addLayer(group2);
map_var.addLayer(group3);

$("#bike").click(function(event) {
    event.preventDefault();
    f(map_var.hasLayer(group1)) {
        map_var.addLayer(group1);                 
        $(this).addClass('selected');
    } else {
        $(this).removeClass('selected');
        map_var.removeLayer(group1);
    }
});

$("#train").click(function(event) {
    event.preventDefault();
    if(map_var.hasLayer(group2)) {
        map_var.addLayer(group2);                 
        $(this).addClass('selected');
    } else {
        $(this).removeClass('selected');
        map_var.removeLayer(group2);
    }
});

$("#pharmacy").click(function(event) {
    event.preventDefault();
    if(map_var.hasLayer(group3)) {
        map_var.addLayer(group3);                 
        $(this).addClass('selected');
    } else {
        $(this).removeClass('selected');
        map_var.removeLayer(group3);
   }
});

我希望创建类似这样的东西。

我是javascript新手,谢谢大家。


1
请阅读关于layerGroup的文档:https://leafletjs.com/examples/layers-control/ - peeebeee
@peeebeee 我尝试在不同的组中添加相同类型的标记,但我不知道如何在地图上添加按钮。我尝试了类似于这个的东西,但我想要像这个那样的东西。 - AliceG
好的,您可以使用layersControl内置按钮(文档的同一页)开始。它非常适用于打开/关闭图层组。 - peeebeee
@peeebeee 我添加了一个图层控制器,但它对我没有作用。似乎我无法在我的图层组和图层控制器之间建立连接。仅有图层组时,我也无法将其关闭。 - AliceG
1个回答

0

这里有一个 jsFiddle演示, 它向OpenStreetMap添加了3种标记:

OpenStreetMap with markers

我的Javascript代码发送以下Overpass API查询以获取具有特定标签的节点:
[out:json][bbox:{{bbox}}];
(
  node[amenity=restaurant];
  node[amenity=fast_food];
  node[amenity=cafe];
);
out center;

节点会被绘制成标记,可以通过选择复选框来显示/隐藏。

按类型删除它们也是可行的,请参考我的源代码中的三个clearLayers()调用:

'use strict';

function processOverpassReply(data) {

  data.elements.forEach(function(element) {
    var amenity = element.tags.amenity;
    var name = element.tags.name;
    var lat = element.lat;
    var lng = element.lon;
      
    L.marker([lat, lng])
      .bindPopup(amenity + '<br>' + name)
      .addTo(groups[amenity]);
  });
}

function sendOverpassRequest() {
  groups.restaurant.clearLayers();
  groups.fast_food.clearLayers();
  groups.cafe.clearLayers();

  var mapBounds = myMap.getBounds();
  var bbox = [
    mapBounds.getWest(),
    mapBounds.getSouth(),
    mapBounds.getEast(),
    mapBounds.getNorth()
  ].join(',');

  var query = '[out:json];(node[amenity=restaurant](bbox);node[amenity=fast_food](bbox);node[amenity=cafe](bbox););out+center;';

  var url = 'https://overpass-api.de/api/interpreter?bbox=' + bbox +
    '&data=' + query;

  var request = new XMLHttpRequest();
  request.open('GET', url, true);
  request.onload = function() {
    if (this.status >= 200 && this.status < 400) {
      var data = JSON.parse(this.response);
      processOverpassReply(data);
    }
  };
  request.send();
}

var startPosition = [51.4661, 7.2491];
var zoomOptions = {
  minZoom: 14,
  maxZoom: 16
};

var myMap = L.map('myMap', zoomOptions).setView(startPosition, 14);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(myMap);

var groups = {
  restaurant: L.featureGroup().addTo(myMap),
  fast_food: L.featureGroup().addTo(myMap),
  cafe: L.featureGroup().addTo(myMap)
};

var overlays = {
  'Show restaurants': groups.restaurant,
  'Show fast food': groups.fast_food,
  'Show cafes': groups.cafe
};

L.control.layers(null, overlays, {
  collapsed: false
}).addTo(myMap);

myMap.on('dragend zoomend', sendOverpassRequest);

sendOverpassRequest();
html,
body {
  margin: 0;
  padding: 0;
}

#myMap {
  position: absolute;
  width: 100%;
  height: 100%;
}
<link href="https://cdn.jsdelivr.net/npm/leaflet@1/dist/leaflet.min.css" type="text/css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/leaflet@1/dist/leaflet-src.min.js"></script>

<div id="myMap"></div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接