skip to Main Content

Good evening. I am new here and I hope I am in the right place asking the right questions!

I am basically just trying to enhance this I found on github https://github.com/voronianski/realtime-geolocation-demo

I have it running with a lot of changes and it displays the map now clearly, I think that old code is really out of date. It all works but it is supposed to show the other connected users but it does not. I cannot do any debugging as I am running it on my cloud server which is running plesk.

I will include my code that seems to be running fine apart from the other others showing on the map. Can anyone help me with why this is. Is it because it is really old code and newer versions of things dont run the same? Well here is my code and thanks if I can get any help.

My server.js

var http = require('http');
var Static = require('node-static');
var app = http.createServer(handler);
var io = require('socket.io').listen(app);
var port = 8080;

var files = new Static.Server('./public');

function handler (request, response) {
    request.on('end', function() {
        files.serve(request, response);
    }).resume();
}

// delete to see more logs from sockets


io.sockets.on('connection', function (socket) {

    socket.on('send:coords', function (data) {
        socket.broadcast.emit('load:coords', data);
    });
});

// start app on specified port
app.listen(port);
console.log('Your server goes on localhost:' + port);

Application.js

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

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

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

    // check whether browser supports geolocation api
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(positionSuccess, positionError, { enableHighAccuracy: true });
    } 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

    var map = L.map('map').fitWorld();

    L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
        maxZoom: 18,
        attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' +
            '<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
            'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
        id: 'mapbox.streets'
    }).addTo(map);
        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 > 15000) {
                delete connects[ident];
                map.removeLayer(markers[ident]);
            }
        }
    }, 15000);
});

and the index.html is

<!DOCTYPE html>
<html>
<head>

    <title>Mobile tutorial - Leaflet</title>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="shortcut icon" type="image/x-icon" href="docs/images/favicon.ico" />

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.3.4/leaflet.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.3.4/leaflet.js"></script>


    <style>
        html, body {
            height: 100%;
            margin: 0;
        }
        #map {
            width: 600px;
            height: 400px;
        }
    </style>

    <style>body { padding: 0; margin: 0; } #map { height: 100%; width: 100vw; }</style>
</head>
<body>

<div id='map'></div>



    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

    <script src="/socket.io/socket.io.js"></script>
    <script src="./js/application.js"></script>


</body>
</html>

I hope this is enough and I have done it correct, I am sorry if I have not. Correct me and I will be change it or add what I have to.

Thankyou, regards Larry

2

Answers


  1. Chosen as BEST ANSWER

    I have it working when I removed the var from var map = L.map('map').fitWorld();

    However it seems to be a little slow to add new users? I know there is a delay in removing them but not adding them. Any suggestions? Thanks


  2. You need add this code. Then you can showing connected users from array sockets

    const sockets = [];
    io.sockets.on('connection', onConnection.bind(this));
    
    function onConnection(socket) {
      socket.on('send:coords', function (data) {
         socket.broadcast.emit('load:coords', data);
      }); 
      sockets.push(socket);
    }
    

    Then delete this code:

    io.sockets.on('connection', function (socket) {
    
        socket.on('send:coords', function (data) {
            socket.broadcast.emit('load:coords', data);
        });
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search