0

What I am trying to do is to use Leaflet with OSM map, and load data from PHP in GeoJSON format + update periodically.

I can manage to display a map, load data, but do not know how to update points instead of still adding a new ones.

function update_position() {


        $.getJSON('link_to_php', function(data) {

            //get data into object
            var geojsonFeature = JSON.parse(data);

            // how to remove here old markers???


            //add new layer
            var myLayer = L.geoJSON().addTo(mymap);

            //add markers to layet
            myLayer.addData(geojsonFeature);

            setTimeout(update_position, 1000);

        });
    }

    update_position();

have tried mymap.removeLayer("myLayer"); but this seems to now work inside of function. Please help

1 Answer 1

2

L.geoJSON extends from LayerGroup which provide a function named clearLayers(docs), so you call that to clear markers from the layer.

Also, it is recommended that you put the layer variable outside the function:

var geoJSONLayer = L.geoJSON().addTo(mymap);

function update_position() {
    $.getJSON('link_to_php', function(data) {   
        //get data into object
        var geojsonFeature = JSON.parse(data);

        geoJSONLayer.clearLayers();

        //add markers to layet
        geoJSONLayer.addData(geojsonFeature);

        setTimeout(update_position, 1000);
    });
}

update_position();
2
  • Thank you this resolve my mentioned issue. However, this solution has one small problem. Markers are "blinking". When I am the refreshing position of the markers, even if is exactly the same markers are blinking on refresh (every 1000 ms). Any idea how to bypass it? Maybe update markers instead of delete and draw again? I will appreciate any help
    – Tikky
    Commented Dec 28, 2018 at 9:39
  • Of course, it looks like blink because you remove it first and add it then. Once your response returned, you can check each feature to see if it exists in the map, just add it if not. In this case, you have to make sure that the features can be distinguished from each other, for example, each feature have a unique id.
    – hguser
    Commented Dec 29, 2018 at 0:38

Not the answer you're looking for? Browse other questions tagged or ask your own question.