Google Map API Integration with Next JS
To get the real-time location, we need to implement the Google Maps Api.
Here is the detailed Documentation of it.
At first, we need to get the Google Maps Api Key. For that, please follow the documentation of: https://developers.google.com/maps/get-started
After getting the api key, install the package:
npm i @googlemaps/js-api-loader
Then secure it in .env.local file and must use NEXT_PUBLIC_ , prefix because without that, the API key won’t be available in client-side code.
Then, create a client component for Map:
"use client";
import { useRef, useEffect } from "react";
import { Loader } from "@googlemaps/js-api-loader";
const Maps = ({ location }) => {
// Create a reference to attach the Google Map
const mapRef = useRef(null);
useEffect(() => {
if (!location) return;
const initMap = async () => {
// Initialize the Google Maps API loader
const loader = new Loader({
apiKey: process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY, // Use env variable for API key
version: "weekly", // Use latest stable version each week
});
const { Map } = await loader.importLibrary("maps"); // Import maps library
const { Marker } = await loader.importLibrary("marker"); // Import marker library
// Define the center position for the map using props
const position = {
lng: location.lng, // Longitude
lat: location.lat, // Latitude
};
// Configure map options
const mapOptions = {
center: position,
zoom: 15,
mapId: "MY_NEXTJS_MAPID", // Optional custom map ID
};
// Create the map using the reference
const map = new Map(mapRef.current, mapOptions);
// Add a marker to the specified position
new Marker({ map, position });
};
initMap();
}, [location]); // Run effect when location changes
return <div style={{ height: "10px" }} ref={mapRef}></div>;
export default Maps;Here we need to understand:
- Ref Hook:
mapRefis used to reference the container where the map will render. - Loader: Loads Google Maps using the API key and version.
- Libraries:
mapsandmarkerare imported separately. - Location Dependency: The map is only initialized when a valid location is provided.
- Position: Longitude and latitude are passed to center the map and place a marker.
Then Getting the User’s Location:
Get Rabeya Akter’s stories in your inbox
Join Medium for free to get updates from this writer.
In your PrefferedLocation component:
Here:
navigator.geolocation: Native web API to access the user's current location.
getCurrentPosition: Returnslatitudeandlongitude.setLocation: Updates local state with{ lng, lat }used in the Map component.localStorage: Saves both location and radius for further use.
4. Rendering Map Conditionally:
In location.lat, location.lng it will show us the current location.





