Developing a Live Location App
Before starting, ensure you have the following installed:
Node.js and npm (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:
mkdir live-location-app
cd live-location-app
- Initialize a new Node.js project:
npm init -y
- Install the required dependencies:
npm install express ejs socket.io
2. Setting Up the Server
Create a server.js file and set up the Express server and Socket.IO.
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const path = require('path');
const app = express();
const server = http.createServer(app);
const io = new Server(server);
// Set up EJS as the view engine
app.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 page
app.get('/', (req, res) => {
res.render('index');
});
// Socket.IO connection
io.on('connection', (socket) => {
console.log('A user connected:', socket.id);
// Listen for location updates from the client
socket.on('updateLocation', (location) => {
console.log('Location received:', location);
// Broadcast the location to all connected clients
io.emit('newLocation', { id: socket.id, location });
});
// Handle disconnection
socket.on('disconnect', () => {
console.log('A user disconnected:', socket.id);
});
});
// Start the server
const PORT = 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 the leaflet.css
and leaflet.js
files in the public
folder.
4. views/index.ejs
Add Leaflet's CSS and JS files to the EJS template.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Live Location Sharing</title>
<link rel="stylesheet" href="/leaflet.css">
<link rel="stylesheet" href="/style.css">
</head>
<body>
<h1>Live Location Sharing</h1>
<div id="map"></div>
<script src="/leaflet.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script src="/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: 20px 0;
}
#map {
height: 500px;
width: 90%;
margin: 0 auto;
border: 2px solid #ccc;
border-radius: 10px;
}
6.main.js
Integrate Leaflet to display the user's live and other users' locations.
const socket = io();
// Initialize the map
const map = 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 user
let userMarker = null;
// Check if Geolocation is supported
if ('geolocation' in navigator) {
navigator.geolocation.watchPosition(
(position) => {
const { latitude, longitude } = position.coords;
// Send the location to the server
socket.emit('updateLocation', { latitude, longitude });
// Update the map with the user's location
if (!userMarker) {
userMarker = L.marker([latitude, longitude]).addTo(map)
.bindPopup('My Location')
.openPopup();
} else {
userMarker.setLatLng([latitude, longitude]);
}
// Center the map on the user's location
map.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 users
socket.on('newLocation', (data) => {
console.log('New location received:', data);
// Add or update a marker for the other user
if (!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 the connection
event.
io.on('connection', (socket) => {
console.log('A user connected');
});
- Emitting Events
You can send data between the client and server using socket.emit()
.
socket.emit('customEvent', { message: 'Hello, client!' });
- Listening for Events
The client can listen for events from the server using socket.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 the disconnect
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)