user9966589
user9966589

Reputation:

automatically remove previous marker and add new marker on map by click event in leaflet.js

I want my map automatically remove old marker and add new marker by clicking, but I don't know how to do it.

var mapOptions = {
    center: [17.385044, 78.486671],
    zoom: 10
}
var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');
var map = new L.map('mapid', mapOptions);
map.addLayer(layer);

map.on("click", function(e) {
    var mp = null;
    if (mp !== null) {
        map.removeLayer(mp);
    }
    var mp = new L.Marker([e.latlng.lat, e.latlng.lng]).addTo(map);
    alert(mp.getLatLng());
})

Upvotes: 0

Views: 2030

Answers (1)

Alex
Alex

Reputation: 2174

You need to keep track of previously created markers and remove them from the map on click event.

Here is a basic example describing how to remove/add Leaflet marker:

HTML:

<div id="map" data-mode="">

</div>

JS:

// add a tile layer to our map
var url = 'http://{s}.tile.osm.org/{z}/{x}/{y}.png';
var attr = '&copy; <a href="http://openstreetmap.org/copyright">OpenStreetMap</a> contributors',
  osm = L.tileLayer(url, {
    maxZoom: 18,
    attribution: attr
  });


// initialize the map 
var map = L.map('map').setView([25.92, 79.84], 5).addLayer(osm);

// click event
map.on('click', onMapClick);

// markers storage
var markers = [];

// Script for adding marker on map click
function onMapClick(e) {

  var geojsonFeature = {
    "type": "Feature",
    "properties": {},
    "geometry": {
      "type": "Point",
      "coordinates": [e.latlng.lat, e.latlng.lng]
    }
  }
  // remove previous marker
  if (markers.length > 0) {
    map.removeLayer(markers.pop());
  }
  var marker;

  L.geoJson(geojsonFeature, {

    pointToLayer: function(feature, latlng) {

      marker = L.marker(e.latlng, {

        title: "Resource Location",
        alt: "Resource Location",
        riseOnHover: true,
        draggable: true,

      });
      markers.push(marker)

      return marker;
    }
  }).addTo(map);
}

Here is jsfiddle.

Upvotes: 1

Related Questions