
Developing a Live Location App
Before starting, ensure you have the following installed:
Node.js andnpm (Node Package Manager)
Basic knowledge of JavaScript, Express, and EJS.
Project Structure
live-location-app/│├── views/│ ├── index.ejs│├── public/│ ├── style.css│ ├── main.js│ ├── leaflet.css│ ├── leaflet.js│├── server.js├── package.json
1. Setting Up the Project
- Create a new directory for your project:
mkdirlive-location-appcdlive-location-app
- Initialize a new Node.js project:
npm init-y
- Install the required dependencies:
npminstallexpress ejs socket.io
2. Setting Up the Server
Create a server.js file and set up the Express server and Socket.IO.
constexpress=require('express');consthttp=require('http');const{Server}=require('socket.io');constpath=require('path');constapp=express();constserver=http.createServer(app);constio=newServer(server);// Set up EJS as the view engineapp.set('view engine','ejs');app.set('views',path.join(__dirname,'views'));// Serve static files (CSS, JS)app.use(express.static(path.join(__dirname,'public')));// Render the index pageapp.get('/',(req,res)=>{res.render('index');});// Socket.IO connectionio.on('connection',(socket)=>{console.log('A user connected:',socket.id);// Listen for location updates from the clientsocket.on('updateLocation',(location)=>{console.log('Location received:',location);// Broadcast the location to all connected clientsio.emit('newLocation',{id:socket.id,location});});// Handle disconnectionsocket.on('disconnect',()=>{console.log('A user disconnected:',socket.id);});});// Start the serverconstPORT=process.env.PORT||3333;server.listen(PORT,()=>{console.log(`Server is running on http://localhost:${PORT}`);});
3. Add Leaflet Files
Download the Leaflet CSS and JS files from the official website:https://leafletjs.com/.
Place theleaflet.css
andleaflet.js
files in thepublic
folder.
4.views/index.ejs
Add Leaflet's CSS and JS files to the EJS template.
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>Live Location Sharing</title><linkrel="stylesheet"href="/leaflet.css"><linkrel="stylesheet"href="/style.css"></head><body><h1>Live Location Sharing</h1><divid="map"></div><scriptsrc="/leaflet.js"></script><scriptsrc="/socket.io/socket.io.js"></script><scriptsrc="/main.js"></script></body></html>
5.style.css
Add some basic styling for the map.
body{font-family:Arial,sans-serif;text-align:center;margin:0;padding:0;}h1{margin:20px0;}#map{height:500px;width:90%;margin:0auto;border:2pxsolid#ccc;border-radius:10px;}
6.main.js
Integrate Leaflet to display the user's live and other users' locations.
constsocket=io();// Initialize the mapconstmap=L.map('map').setView([0,0],13);// Default center and zoom level// Add a tile layer (you can use OpenStreetMap or other providers)L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',{attribution:'© <a href="https://gravatar.com/floawd">developer</a>'}).addTo(map);// Marker for the current userletuserMarker=null;// Check if Geolocation is supportedif('geolocation'innavigator){navigator.geolocation.watchPosition((position)=>{const{latitude,longitude}=position.coords;// Send the location to the serversocket.emit('updateLocation',{latitude,longitude});// Update the map with the user's locationif(!userMarker){userMarker=L.marker([latitude,longitude]).addTo(map).bindPopup('My Location').openPopup();}else{userMarker.setLatLng([latitude,longitude]);}// Center the map on the user's locationmap.setView([latitude,longitude],13);},(error)=>{console.error('Error getting location:',error);},{enableHighAccuracy:true});}else{alert('Geolocation is not supported by your browser.');}// Listen for new locations from other userssocket.on('newLocation',(data)=>{console.log('New location received:',data);// Add or update a marker for the other userif(!window.otherMarkers){window.otherMarkers={};}const{id,location}=data;if(!window.otherMarkers[id]){window.otherMarkers[id]=L.marker([location.latitude,location.longitude]).bindPopup(`User${id}`).addTo(map);}else{window.otherMarkers[id].setLatLng([location.latitude,location.longitude]);}});
7. Explanation of the Code
Leaflet Map Initialization:
- The map is initialized with a default center (
[0, 0]
) and zoom level (13
). - A tile layer (OpenStreetMap) is added to the map.
- The map is initialized with a default center (
User Location:
- The
geolocation.watchPosition
API continuously tracks the user's location. - A marker is created for the user and updated as their location changes.
- The
Other Users' Locations:
- When the server broadcasts a new location (
newLocation
), a marker is created or updated for that user.
- When the server broadcasts a new location (
Socket.IO:
- The client sends the user's location to the server using
updateLocation
. - The server broadcasts the location to all clients using
newLocation
.
- The client sends the user's location to the server using
8. Running the App
- Start the server:
node server.js
Open your browser and navigate to
http://localhost:3333
.Allow the browser to access your location. You should see your live location on the map.
Open the app in another browser or device. You'll see both users' locations on the map in real-time.
9. Example Output
- The map will display your location with a "My Location" marker.
- Other users' locations will appear as markers labeled "User [ID]".
- The map will automatically center on your location.
10. Understanding Socket.IO Events
- Connection Event
Every new user triggers theconnection
event.
io.on('connection',(socket)=>{console.log('A user connected');});
- Emitting Events
You can send data between the client and server usingsocket.emit()
.
socket.emit('customEvent',{message:'Hello, client!'});
- Listening for Events
The client can listen for events from the server usingsocket.on()
.
socket.on('customEvent',(data)=>{console.log(data.message);});
- Broadcasting Messages
To send a message to all connected clients except the sender:
socket.broadcast.emit('updateLocation',data);
- Handling Disconnections
When a user leaves, handle thedisconnect
event:
socket.on('disconnect',()=>{console.log('User disconnected');});
11. Scaling Socket.IO Applications
For larger applications, consider:
- Using Redis for scaling WebSocket connections
- Implementing authentication for secure communication
- Handling rooms for group-based communication
- Deploying with Nginx for WebSocket support

Realtime Location Tracker & Communications
Mahmudur Rahman ・ Dec 20 '24
Follow for more!
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse