Sun
Sun

Reputation: 23

Leaflet - how to remove previous marker automatically

the following javascript code will enable the creation of markers on the map on map click local and global in realtime with node.js / socket.io. This works fine but each added marker is visible.

like this example: http://jsfiddle.net/brettdewoody/LK35U/

Now, when the second marker has been added to the map, I need to remove the previous marker (first one) automatically, then add 3rd marker -> remove 2nd marker and so on. Can anyone help me understand how to do this? Maybe with grouplayer? How does it work?

// generate unique user id
var userId = Math.random().toString(16).substring(2,15);

var socket = io.connect('http://localhost:4000');
var doc = $(document);

// custom marker's icon styles
var tinyIcon = L.Icon.extend({
    options: {
        iconSize: [25, 39],
        iconAnchor:   [12, 36],
        shadowSize: [41, 41],
        shadowAnchor: [12, 38],
        popupAnchor: [0, -30]
    }
});
var anyIcon = new tinyIcon({ iconUrl: "assets/img/icon.png" });

var sentData = {}

var connects = {};
var markers = {};
var active = false;

// for node.js send coords and set marker (global)
socket.on("load:coords", function(data) {
    setMarker(data);

    connects[data.id] = data;
    connects[data.id].updated = $.now(); // shorthand for (new Date).getTime()
    console.log(data);
});


// set marker (local)
function addMarker(position) {
    var lat = position.latlng.lat;
    var lng = position.latlng.lng;

    // mark user's position
    var userMarker = L.marker([lat, lng], {
        icon: myIcon,
    });

    userMarker.addTo(map);
    userMarker.bindPopup("<p>Your ID is " + userId + "</p>").openPopup();

    // send coords on when user is active
    doc.on("click", function() {
        active = true; 

        sentData = {
            id: userId,
            active: active,
            coords: [{
                lat: lat,
                lng: lng,
            }]
        }
        socket.emit("send:coords", sentData);
    });
}

doc.bind("mouseup mouseleave", function() {
    active = false;
});

// showing markers for connections
function setMarker(data) {
    for (i = 0; i < data.coords.length; i++) {
        var marker = L.marker([data.coords[i].lat, data.coords[i].lng], { icon: yellowIcon}).addTo(map);
        marker.bindPopup("<p>Your ID is " + data.id + "</p>").openPopup();
        markers[data.id] = marker;
    }
}

map.on('click', addMarker);

EDIT:

Thanks for your quick answer @iH8! Your solution works fine for me local. But now when other users join (via node.js) and add markers to the map, the markers(lat/lng) of unique userId will be save in an array.

// for node.js send coords and set marker (global)
socket.on("load:coords", function(data) {
setMarker(data);

connects[data.id] = data;
connects[data.id].updated = $.now(); // shorthand for (new Date).getTime()
console.log(data);
});

this will send the data.coords (lat/lng) of userId and add to the map:

// showing markers for connections
function setMarker(data) {
    for (i = 0; i < data.coords.length; i++) {
        var marker = L.marker([data.coords[i].lat, data.coords[i].lng], { icon: yellowIcon}).addTo(map);
        marker.bindPopup("<p>Your ID is " + data.id + "</p>").openPopup();
        markers[data.id] = marker;
        console.log('ID: ' + data.id + ' LAT: ' + data.coords[i].lat + ' LNG: ' + data.coords[i].lng);
    }
}

The first add to map click is still O.K.

console.log:

ID: 74274f99 LAT: 46.34692761055676 LNG: 8.8330078125

now the second click of the same user / UNIQUE userId console.log:

ID: 74274f99 LAT: 46.34692761055676 LNG: 8.8330078125
ID: 74274f99 LAT: 44.5278427984555 LNG: 9.404296875

Here the console.log shows me the same userId with two different LAT/LNG because of the second click. The effect is, now I see 2 markers with different LAT/LNG on the map. But I just want to see only the latest one:

ID: 74274f99 LAT: 44.5278427984555 LNG: 9.404296875

How can I remove the first/old one? I'm confused.

Upvotes: 2

Views: 13373

Answers (1)

iH8
iH8

Reputation: 28638

You can remove layers from the map using the removeLayer function of L.Map. A marker is also seen as a layer in Leaflet. So in your onclick handler, first remove the current marker, then create a new marker and add to the map. Something like this will do the trick:

var marker = null;

map.on('click', function (e) {
    if (marker !== null) {
        map.removeLayer(marker);
    }
    marker = L.marker(e.latlng).addTo(map);
});

Working example on Plunker: http://plnkr.co/edit/NRl0VQi3wSGK3p8aHlHs?p=preview

EDIT: After rereading your question i've got a better understanding of what you are trying to accomplish. I think this is what you are looking for:

var myId = 'abc'; // My user id

// other user id's and their markers
var markers = {
    'def': L.marker([51.441767, 5.470247]).addTo(map),
    'ghi': L.marker([51.441767, 5.480247]).addTo(map),
    'jkl': L.marker([51.441767, 5.490247]).addTo(map)
};

map.on('click', function (e) {
    // check if my user id in marker object and thus on the map
    if (markers.hasOwnProperty(myId)) {
        // remove the marker
        map.removeLayer(markers[myId]);
    }
    // place (or overwrite) marker with my uid in object and add to map
    markers[myId] = L.marker(e.latlng).addTo(map);
});

Here's another working example on Plunker: http://plnkr.co/edit/X8NQVF1FDbNKTV5a5nwn?p=preview

Upvotes: 14

Related Questions