Creating a Google Map in Next.js Without Third-Party Libraries

Vandanaba Gohil By Vandanaba Gohil ·
Creating a Google Map in Next.js Without Third-Party Libraries

Hey there, fellow developers! Today, I want to walk you through a neat way to display a Google Map in a Next.js application without relying on any third-party libraries. Let’s dive into the code and break it down into understandable sections.

1. Importing Dependencies

We start by importing the necessary React hooks, useRef and useEffect:

import React, { useRef, useEffect } from 'react';

2. Defining the Props

Our GoogleMapProps interface defines the props that our component will accept:

interface GoogleMapProps {
    apiKey: string;
    zoom: number;
    center: google.maps.LatLngLiteral;
    markerPosition: google.maps.LatLngLiteral;
}
  • apiKey: Your Google Maps API key.
  • zoom: The initial zoom level of the map.
  • center: The initial center position of the map, as a latitude and longitude literal.
  • markerPosition: The position of the marker on the map.

3. Setting Up the Map Container

We create the MapContainer functional component and initialize a reference to the map container div:

const MapContainer: React.FC<GoogleMapProps> = ({ apiKey, zoom, center, markerPosition }) => {
    const mapRef = useRef<HTMLDivElement>(null);
    let map: google.maps.Map;

    useEffect(() => {
        map = new window.google.maps.Map(mapRef.current!, {
            center,
            zoom,
        });

        new google.maps.Marker({
            position: markerPosition,
            map: map,
            title: 'Marker Title',
        });
    }, [center, zoom, markerPosition]);

Here, mapRef is a reference to the HTML div element that will contain the map. map will hold the instance of the Google Map.

4. Loading the Google Maps Script

In Next.js, we use the Script component to load external scripts. Here's how you would do it:

import Script from 'next/script'

<Script src={`https://maps.googleapis.com/maps/api/js?key=${apiKey}&libraries=places`} />

5. Rendering the Map Container

Finally, we return a div that will contain the map. We use the ref attribute to link this div to our mapRef reference. We also style it to ensure it has dimensions:

return <div ref={mapRef} style={{ width: '100%', height: '400px' }} />;

This div will act as the container for the Google Map, and it’s crucial to give it a size; otherwise, the map won’t be visible.

6. Placing the Marker

Inside the useEffect hook, we create a new marker and associate it with the map:

marker = new google.maps.Marker({
    position: markerPosition,
    map,
    title: 'Marker Title',
});

7. Exporting the Component

We export the component so it can be used in other parts of our application:

export default MapContainer;

The Code

Here’s the complete code for our MapContainer component:

import React, { useRef, useEffect } from 'react'; interface GoogleMapProps { apiKey: string; zoom: number; center: google.maps.LatLngLiteral; markerPosition: google.maps.LatLngLiteral; } const MapContainer: React.FC<GoogleMapProps> = ({ apiKey, zoom, center, markerPosition }) => { const mapRef = useRef<HTMLDivElement>(null); let map: google.maps.Map; useEffect(() => { const mapRef = useRef<HTMLDivElement>(null); let map: google.maps.Map; useEffect(() => { map = new window.google.maps.Map(mapRef.current!, { center, zoom, }); new google.maps.Marker({ position: markerPosition, map: map, title: 'Marker Title' }); }, []); return <div ref={mapRef} style={{ width: '100%', height: '400px' }} />; }; export default MapContainer;

Using the MapContainer Component

To use the MapContainer component, simply import it and provide the necessary props. Here’s an example of how you might use it in a page component:

import MapContainer from './components/MapContainer'; const Home = () => { const zoom = 10; const center = { lat: 37.7749, lng: -122.4194 }; const markerPosition = { lat: 37.7749, lng: -122.4194 }; return ( <div> <h1>My Google Map</h1> <MapContainer zoom={zoom} center={center} markerPosition={markerPosition} /> </div> ); }; export default Home;

In this example, you can adjust the zoom, center, and markerPosition to suit your needs.

Wrapping Up

And there you have it! We’ve created a Google Map in a Next.js application without relying on any third-party libraries. This approach gives you full control over how you load and interact with the Google Maps API.

Feel free to experiment with different map options and markers. You can customize the map further by exploring the Google Maps JavaScript API documentation. Happy coding!


Remain Ahead of the Curve

Stay upto date with the latest Technologies, Trends, Artificial Intelligence, Productivity Tips and more.

No spam. You can unsubscribe at any time.