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

问题描述 投票:0回答:1

我在传单地图上添加添加/删除标记的功能时遇到问题。我阅读并尝试了很多不同的代码,但我不明白如何删除精确类型的所有标记。我的代码是这样的:

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

我想创建像this.

这样的东西

我是 javascript 的新手,谢谢大家。

javascript leaflet coordinates openstreetmap markers
1个回答
0
投票

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

您可以通过选中复选框来显示/隐藏标记。

按类型删除它们也在那里,请参阅我的 Javascript 代码中的

clearLayers
调用:

'use strict';

function processOverpassReply(data) {
  console.log(data);

  data.elements.forEach(function(element) {
    if (element.type === 'node') {
      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() {
  removeAllMarkers();

  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;

  console.log('Calling Overpass API URL: ' + url);

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

function removeAllMarkers() {
  groups['restaurant'].clearLayers();
  groups['fast_food'].clearLayers();
  groups['cafe'].clearLayers();
}

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('moveend', sendOverpassRequest);

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.