Tracking User Location in React with the Geolocation API
By O. Wolfson
Getting location...
🗺️ Displaying User Location on a Map with Leaflet
Adding real-time maps to your Next.js application can make your user experience more engaging and location-aware. With the HTML5 Geolocation API and the Leaflet mapping library, it's straightforward to display the user's current location on an interactive map.
🧭 What We're Building
We'll build a React component that:
Uses the Geolocation API to get the user's location
import dynamic from"next/dynamic";
// Dynamically import Leaflet (it uses window object, so SSR must be disabled)constUserLocationMap = dynamic(() =>import("@/components/UserLocationMap"), {
ssr: false,
});
exportdefaultfunctionPage() {
return (
<mainclassName="p-6 max-w-2xl mx-auto"><UserLocationMap /></main>
);
}
📦 Installation Requirements
To use this in your project, install the required packages:
bash
npm install leaflet react-leaflet
You may also need to configure your Next.js project to handle image imports. If you're using Webpack, this is typically handled automatically. In a Next.js app with the App Router, it should work without changes if you're using Next 13.4+.
🔐 A Note on Privacy
Always request location data responsibly. The user must grant permission, and their data should never be shared without explicit consent.