Open In App

How to Add Google Maps to a Website ?

Integrating Google Maps into a website is a common and useful feature. We can use Google Maps API to add it to our website.

Follow the below steps to Add Google Maps to a Website

1. Generate/Obtain Google Maps API Key

To fetch the location data from Google Maps first we need a Google Maps API Key. It is required to authorize the collection of the data from Google Maps. These are the steps to generate a Google Maps API Key:



2. Create an HTML Container for the map

After the generation of API key we are going to create an HTML div. Inside that div our map will remain. We will do this in the following steps:



<div id="map"></div>

3. Style the map container:

#map {
height: 400px; /* Adjust height as needed */
width: 100%; /* Adjust width as needed */
}

4. Add an external script by google inside the HTML document

Add the following async script inside the HTML document as it executes immediately and must be after any DOM elements used in callback. Inside the script URL put the API key we generated earlier replacing the ‘<YOUR_API_KEY>’ section.

<script src= “https://maps.googleapis.com/maps/api/js?key=<YOUR_API_KEY>&callback=initMap&libraries=&v=weekly” async> </script>

5. Write JavaScript code to bring the map inside that container

After the creation of the container we have to write the JavaScript code that actually brings the map inside the container. This is the main part where we generate the map.

6. Test your map:

Example: Below is implementation of the approach.




<!DOCTYPE html>
<html>
 
<head>
    <style type="text/css">
 
        /* Set the size of the div element
        that contains the map */
        #map {
            height: 400px;
            width: 400px;
        }
         
        h2 {
            color: #308d46;
        }
    </style>
</head>
 
<body>
    <h2>
        Add Google Map on Your
        Webpage: Geeksforgeeks
    </h2>
 
    <!--The div element for the map -->
    <div id="map"></div>
 
    <!--Add a script by google -->
    <script src=
"https://maps.googleapis.com/maps/api/js?key=<YOUR_API_KEY>&callback=initMap&libraries=&v=weekly"
        async>
    </script>
 
    <script>
 
        // Initialize and add the map
        function initMap() {
 
            // The location of Geeksforgeeks office
            const gfg_office = {
                lat: 28.50231,
                lng: 77.40548
            };
 
            // Create the map, centered at gfg_office
            const map = new google.maps.Map(
                    document.getElementById("map"), {
 
                // Set the zoom of the map
                zoom: 17.56,
                center: gfg_office,
            });
        }
    </script>
</body>
 
</html>

Output:


Article Tags :