Search code examples
javascriptleafletopenstreetmap

Remove pin/marker on second click with leaflet.js in OSM?


Placing of markers works fine, but now I want if client set wrong marker (wrong place) to be able to click on already placed marker and delete it (after confirmation). The question is: Is there a way to handle click over already placed marker, intead of paste another marker over or close to it?

var mymap = L.map('map').setView([42.148271, 24.750240], 17);

$(document).ready(function() {
    $('#map').css('width', $('.vc_custom_1538133669144').width());
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
        accessToken: 'not-needed',
    }).addTo(mymap)

    L.marker([42.148271, 24.750240]).addTo(mymap);

    mymap.on('click', onMapClick);
});

function onMapClick(e) {
    $('#map').append('<label>test:</label><input type="hidden" name="map_coords"  id="file"  value="' + e.latlng.lat + '|' + e.latlng.lng + '"/>');
    L.marker([e.latlng.lat, e.latlng.lng]).addTo(mymap);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js"></script>
<div id="map" style="height: 500px;">

</div>


Solution

  • Add a click listener to the marker:

    var mymap = L.map('map').setView([42.148271, 24.750240], 17);
    
    $(document).ready(function() {
        $('#map').css('width', $('.vc_custom_1538133669144').width());
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
            accessToken: 'not-needed',
        }).addTo(mymap)
    
        L.marker([42.148271, 24.750240]).addTo(mymap);
    
        mymap.on('click', onMapClick);
    });
    
    function onMapClick(e) {
        $('#map').append('<label>test:</label><input type="hidden" name="map_coords"  id="file"  value="' + e.latlng.lat + '|' + e.latlng.lng + '"/>');
        var marker = L.marker([e.latlng.lat, e.latlng.lng]).addTo(mymap);
        marker.on('click',function(e) { // new code here
            this.remove();
        });
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" />
    <script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js"></script>
    <div id="map" style="height: 500px;">
    
    </div>