Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Creating a Live Location App
Mahmudur Rahman
Mahmudur Rahman

Posted on

Creating a Live Location App

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
Enter fullscreen modeExit fullscreen mode

1. Setting Up the Project

  1. Create a new directory for your project:
mkdirlive-location-appcdlive-location-app
Enter fullscreen modeExit fullscreen mode
  1. Initialize a new Node.js project:
   npm init-y
Enter fullscreen modeExit fullscreen mode
  1. Install the required dependencies:
   npminstallexpress ejs socket.io
Enter fullscreen modeExit fullscreen mode

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}`);});
Enter fullscreen modeExit fullscreen mode

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>
Enter fullscreen modeExit fullscreen mode

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;}
Enter fullscreen modeExit fullscreen mode

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:'&copy; <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]);}});
Enter fullscreen modeExit fullscreen mode

7. Explanation of the Code

  1. 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.
  2. User Location:

    • Thegeolocation.watchPosition API continuously tracks the user's location.
    • A marker is created for the user and updated as their location changes.
  3. Other Users' Locations:

    • When the server broadcasts a new location (newLocation), a marker is created or updated for that user.
  4. Socket.IO:

    • The client sends the user's location to the server usingupdateLocation.
    • The server broadcasts the location to all clients usingnewLocation.

8. Running the App

  1. Start the server:
   node server.js
Enter fullscreen modeExit fullscreen mode
  1. Open your browser and navigate tohttp://localhost:3333.

  2. Allow the browser to access your location. You should see your live location on the map.

  3. 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

  1. Connection Event

Every new user triggers theconnection event.

io.on('connection',(socket)=>{console.log('A user connected');});
Enter fullscreen modeExit fullscreen mode
  1. Emitting Events

You can send data between the client and server usingsocket.emit().

socket.emit('customEvent',{message:'Hello, client!'});
Enter fullscreen modeExit fullscreen mode
  1. Listening for Events

The client can listen for events from the server usingsocket.on().

socket.on('customEvent',(data)=>{console.log(data.message);});
Enter fullscreen modeExit fullscreen mode
  1. Broadcasting Messages

To send a message to all connected clients except the sender:

socket.broadcast.emit('updateLocation',data);
Enter fullscreen modeExit fullscreen mode
  1. Handling Disconnections

When a user leaves, handle thedisconnect event:

socket.on('disconnect',()=>{console.log('User disconnected');});
Enter fullscreen modeExit fullscreen mode

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


Follow for more!

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Full Stack Developer
  • Location
    Bangladesh
  • Education
    Higher study
  • Work
    Freelance web application developer
  • Joined

More fromMahmudur Rahman

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp