Successive markers with navigator.geolocation.watchPosition

你。 提交于 2019-12-25 02:46:40

问题


I use Leaflet and OpenStreetMap. In addition, I send geolocation data with socket.io in nodejs.

The position of the user is displayed successfully with the code:

navigator.geolocation.getCurrentPosition(.........)

Now I want the position of the user is updated on the map every X seconds. So I replaced the code:

navigator.geolocation.watchPosition(.........)

My problem is that a new marker is added geolocation every X seconds, and the oldest markers are not removed.

Could someone help me please?

My js code:

$(function() {
    // generate unique user id
    var userId = Math.random().toString(16).substring(2,15);
    var socket = io.connect('/');


    var info = $('#infobox');
    var doc = $(document);

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

    var sentData = {};

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

    socket.on('load:coords', function(data) {
        if (!(data.id in connects)) {
            setMarker(data);
        }

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

    // check whether browser supports geolocation api
    if (navigator.geolocation) {
        navigator.geolocation.watchPosition(positionSuccess, positionError, { enableHighAccuracy: true, maximumAge : 1000, timeout : 2000 });
    } else {
        $('.map').text('Your browser is out of fashion, there\'s no geolocation!');
    }

    function positionSuccess(position) {
        var lat = position.coords.latitude;
        var lng = position.coords.longitude;
        var acr = position.coords.accuracy;

        // mark user's position
        var userMarker = L.marker([lat, lng], {
            icon: redIcon
        });
        // uncomment for static debug
        // userMarker = L.marker([51.45, 30.050], { icon: redIcon });

        // load leaflet map


        // leaflet API key tiler


        // set map bounds

        userMarker.addTo(map);
        userMarker.bindPopup('<p>You are there! Your ID is ' + userId + '</p>').openPopup();

        var emit = $.now();
        // send coords on when user is active
        doc.on('mousemove', function() {
            active = true;

            sentData = {
                id: userId,
                active: active,
                coords: [{
                    lat: lat,
                    lng: lng,
                    acr: acr
                }]
            };

            if ($.now() - emit > 30) {
                socket.emit('send:coords', sentData);
                emit = $.now();
            }
        });
    }

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

    // showing markers for connections
    function setMarker(data) {
        for (var 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>One more external user is here!</p>');
            markers[data.id] = marker;
        }
    }

    // handle geolocation api errors
    function positionError(error) {
        var errors = {
            1: 'Authorization fails', // permission denied
            2: 'Can\'t detect your location', //position unavailable
            3: 'Connection timeout' // timeout
        };
        showError('Error:' + errors[error.code]);
    }

    function showError(msg) {
        info.addClass('error').text(msg);

        doc.click(function() {
            info.removeClass('error');
        });
    }

    // delete inactive users every 15 sec
    setInterval(function() {
        for (var ident in connects){
            if ($.now() - connects[ident].updated > 30000) {
                delete connects[ident];
                map.removeLayer(markers[ident]);
            }
        }
    }, 30000);
});

回答1:


I suppose this would be basically the same issue as discussed in Move Marker question.

Thus, simply remove the earlier marker before you add new one..



来源:https://stackoverflow.com/questions/22959535/successive-markers-with-navigator-geolocation-watchposition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!