How to Develop a Live Location Tracking System with WebSockets, Golang, ReactJS, and Google Maps


1. Introduction
This enhancement involves using the Geolocation API to get the user's coordinates and the Google Maps API to display the user's location.
2. Setting Up the Backend with Golang
Initializing the Project
First, ensure you have Golang installed. Create a new directory for your project and initialize a Go module:
mkdir tracking-system
cd tracking-system
go mod init tracking-system
Implementing WebSocket Server
Install the Gorilla WebSocket package:
go get github.com/gorilla/websocket
Create a main.go
file and set up a basic WebSocket server:
package main
import (
"log"
"net/http"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
func handleConnections(w http.ResponseWriter, r *http.Request) {
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Fatal(err)
}
defer ws.Close()
for {
var msg string
err := ws.ReadJSON(&msg)
if err != nil {
log.Printf("error: %v", err)
break
}
log.Printf("Received: %s", msg)
err = ws.WriteJSON(msg)
if err != nil {
log.Printf("error: %v", err)
break
}
}
}
func main() {
http.HandleFunc("/ws", handleConnections)
log.Println("Server started on :8080")
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
This code sets up a WebSocket server that listens on port 8080 and echoes back any messages it receives.
3. Creating the Frontend with ReactJS
Getting User's Location
First, we'll use the Geolocation API to get the user's coordinates. Update your WebSocketComponent.js
to include this functionality:
import React, { useEffect, useState } from 'react';
const WebSocketComponent = () => {
const [message, setMessage] = useState('');
const [socket, setSocket] = useState(null);
const [location, setLocation] = useState({ lat: null, lng: null });
useEffect(() => {
const ws = new WebSocket('ws://localhost:8080/ws');
setSocket(ws);
ws.onmessage = (event) => {
const receivedMessage = JSON.parse(event.data);
setMessage(receivedMessage);
};
return () => {
ws.close();
};
}, []);
useEffect(() => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
setLocation({
lat: position.coords.latitude,
lng: position.coords.longitude,
});
});
} else {
alert("Geolocation is not supported by this browser.");
}
}, []);
const sendMessage = () => {
if (socket) {
socket.send(JSON.stringify("Hello, Server!"));
}
};
return (
<div className="flex flex-col items-center justify-center min-h-screen bg-gray-100">
<h1 className="text-2xl font-bold mb-4">WebSocket Tracking</h1>
<p className="mb-4">Received Message: {message}</p>
<button
onClick={sendMessage}
className="px-4 py-2 bg-blue-500 text-white rounded"
>
Send Message
</button>
{location.lat && location.lng ? (
<p className="mt-4">
Your Location: {location.lat}, {location.lng}
</p>
) : (
<p className="mt-4">Getting location...</p>
)}
</div>
);
};
export default WebSocketComponent;
Integrating Google Maps
Next, we'll integrate Google Maps to show the user's location. Install the @react-google-maps/api
package:
npm install @react-google-maps/api
Create a new component, MapComponent.js
, to handle the map display:
import React from 'react';
import { GoogleMap, LoadScript, Marker } from '@react-google-maps/api';
const MapComponent = ({ location }) => {
const mapContainerStyle = {
width: '100%',
height: '400px',
};
const center = {
lat: location.lat,
lng: location.lng,
};
return (
<LoadScript googleMapsApiKey="YOUR_GOOGLE_MAPS_API_KEY">
<GoogleMap
mapContainerStyle={mapContainerStyle}
center={center}
zoom={15}
>
<Marker position={center} />
</GoogleMap>
</LoadScript>
);
};
export default MapComponent;
Update your WebSocketComponent.js
to include the MapComponent
:
import React, { useEffect, useState } from 'react';
import MapComponent from './MapComponent';
const WebSocketComponent = () => {
const [message, setMessage] = useState('');
const [socket, setSocket] = useState(null);
const [location, setLocation] = useState({ lat: null, lng: null });
useEffect(() => {
const ws = new WebSocket('ws://localhost:8080/ws');
setSocket(ws);
ws.onmessage = (event) => {
const receivedMessage = JSON.parse(event.data);
setMessage(receivedMessage);
};
return () => {
ws.close();
};
}, []);
useEffect(() => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
setLocation({
lat: position.coords.latitude,
lng: position.coords.longitude,
});
});
} else {
alert("Geolocation is not supported by this browser.");
}
}, []);
const sendMessage = () => {
if (socket) {
socket.send(JSON.stringify("Hello, Server!"));
}
};
return (
<div className="flex flex-col items-center justify-center min-h-screen bg-gray-100">
<h1 className="text-2xl font-bold mb-4">WebSocket Tracking</h1>
<p className="mb-4">Received Message: {message}</p>
<button
onClick={sendMessage}
className="px-4 py-2 bg-blue-500 text-white rounded"
>
Send Message
</button>
{location.lat && location.lng ? (
<div className="mt-4">
<p>Your Location: {location.lat}, {location.lng}</p>
<MapComponent location={location} />
</div>
) : (
<p className="mt-4">Getting location...</p>
)}
</div>
);
};
export default WebSocketComponent;
Replace "YOUR_GOOGLE_MAPS_API_KEY"
with your actual Google Maps API key.
4. Styling with Tailwind CSS
Tailwind CSS is already set up and used in the components. You can customize the styling further as needed.
5. Integrating and Running the Application
Ensure all components are correctly imported and used in your App.js
:
import React from 'react';
import WebSocketComponent from './WebSocketComponent';
function App() {
return (
<div className="App">
<WebSocketComponent />
</div>
);
}
export default App;
Subscribe to my newsletter
Read articles from Oluwajuwon Falore directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Oluwajuwon Falore
Oluwajuwon Falore
I am a full-Stack (backend leaning) software developer. Experienced with all stages of the development cycle for dynamic web projects. Well-versed in programming languages including HTML5, CSS, JAVASCRIPT, NODEJS, GOLANG, REACTJS, PYTHON, ANGULAR and IONIC.