Reputation: 81
I've got a problem adding function for add/delete markers on leaflet map. I read and tried lot of different code, but I don't understand how to remove all markers of a precise type. My code is like this:
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: '© <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"}
}
});
When I write the button's code, all of the map disappear. I want to add a button to click by the user and show or not the markers of a precise type (so 3 total buttons).
EDIT: I tried this code too, but it doesn't work:
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: '© <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);
}
});
I want to create something like this.
I'm new with javascript, thank you all.
Upvotes: 4
Views: 2350
Reputation: 23018
Here a jsFiddle demo, which adds 3 kinds of markers to the OpenStreetMap:
My Javascript code sends the following Overpass API query to fetch nodes with specific tags:
[out:json][bbox:{{bbox}}];
(
node[amenity=restaurant];
node[amenity=fast_food];
node[amenity=cafe];
);
out center;
The nodes are then drawn as markers and they can be shown/hidden by selecting a checkbox.
Removing them by type is also there, refer to the three clearLayers()
calls in my source code:
'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: '© <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>
Upvotes: 0