Sabbir Ahmed

Sabbir Ahmed

1 month ago

Google Maps API Integration: Embed Google Maps with Iframe

Now a days, Google map has become very popular and common for using maps in different kind of desktop and mobile applications. For web applications, you will have to work with google maps for various kind of requirements. There are many ways that you can integrate maps in a web application. Google provides a wide range of APIs to do that, such as Maps Javascript Api, Places Api etc. They also have free and paid versions, where free versions can also have the limitations on API uses. But for basic uses, for example, integrating a map location in a contact form, we can use a alternative way where we dont need a API or something. It is also free to use. Today we will see the basic to API service integration for google maps in our websites. 

Adding Google Maps to Your Site Without API Usage


Lets assume you want to share a location for your contact page with google map. For that, please go to google maps and collect the latitude and longitude for the location. Please keep a note of these numbers for further reference.

Now we will use iframe to share a location. Lets see this code example:
 


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Google Map Integration</title>
    <style>
        body {
            font-family: Arial, sans-serif;
        }
        .map-container {
            width: 100%;
            height: 400px;
            margin: 20px 0;
        }
    </style>
</head>
<body>

<h1>My Location</h1>
<div class="map-container">
    <iframe 
        id="mapFrame"
        width="100%" 
        height="400" 
        frameborder="0" 
        style="border:0">
    </iframe>
</div>

<script>
    function updateMap() {
        let latitude = prompt("Enter latitude:");
        let longitude = prompt("Enter longitude:");
        
        if (latitude && longitude) {
            let mapFrame = document.getElementById("mapFrame");
            let src = `https://maps.google.com/maps?q=${latitude},${longitude}&z=15&output=embed`;
            mapFrame.src = src;
        } else {
            alert("Latitude and longitude are required.");
        }
    }

    // Call the function to prompt the user for latitude and longitude
    updateMap();
</script>

</body>
</html>


Note: When you run this code, it will ask for latitude and longitude to enter, you can give the copied latitude and longitude data here. You will see, the map will be pointed via the Iframe src to your expected location. 

You can use this code for your own customization in your page. 

  • How would I make customizations to the map view


Though its a very basic use for integrating the maps, you can make some customizations as your requirement through the query parameters we pass with the src data. Lets see some customization example: 

Adjust map zoom level: You can adjust the maps zoom level via ‘&z=’ parameter: 


<iframe src="https://maps.google.com/maps?q=37.7749,-122.4194&z=10&output=embed" width="100%" height="400" frameborder="0" style="border:0"></iframe>

The more you increase the value of z parameter, the more the map gets zoomed in. 

Change map type: To change map type, you can use ‘&t=’ parameter. For example ‘&t=k’ means the satellite view for map:


 
<iframe src="https://maps.google.com/maps?q=37.7749,-122.4194&z=15&t=k&output=embed" width="100%" height="400" frameborder="0" style="border:0"></iframe>

Here is the possible options for this parameter: 

  • m for Map view (default)
  • k for Satellite view
  • h for Hybrid view
  • p for Terrain view

So this is the basic usage to integrate maps with just latitude and longitude data in your website for free. But if you want do more customizations or for business purpose, you will have to use API provided by google. Please continue reading this article for further knowledge. 

Using Google Maps API for Customization


We know now how to use google maps without any kind of API key. But for advanced and professional use case, you need to avail their services related to google maps, for example: Maps javascript api, or places api etc. Lets see a quick integration demo with maps javascript example:

  • First the api key


Here is a quick guideline to get your API key: 

  1. Go to  Google cloud console
  2. Create a New Project
    • Select new project
    • Enter name and enable billing
    • Click create
    • Enable billing if required
  3. In the search bar, look for Google Maps JavaScript API and enable it
    • You can also find this from APIs & Services > Library
  4.  Now goto APIs & Services > Credentials. 
    • Click on the Create Credentials button and select API key.
    • A dialog will appear with your new API key. 
    • Copy and save it in a note for further usage.

Please have a look at their documentation for further details. 

  • Lets start integrating map


Lets assume you want to share your customer’s business location in their webpage. You have collected their location’s latitude and longitude to show in Google maps. Now in the corresponding page, we need add codes like this:


<!DOCTYPE html>
<html>
<head>
    <title>Google Maps Integration</title>
    <style>
        /* Set the size of the map */
        #map {
            height: 100%;
            width: 100%;
        }
        /* Optional: Make the body full-height for the map */
        html, body {
            height: 100%;
            margin: 0;
            padding: 0;
        }
    </style>
</head>
<body>
    <!-- The div element for the map -->
    <div id="map"></div>

    <!-- Load the Google Maps API script -->
    <script async
        src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>

    <script>
        // Initialize and add the map
        function initMap() {
            // The location you want to center the map on
            const location = { lat: -34.397, lng: 150.644 };

            // The map, centered at the specified location
            const map = new google.maps.Map(document.getElementById("map"), {
                zoom: 8,
                center: location,
            });

            // The marker, positioned at the specified location
            const marker = new google.maps.Marker({
                position: location,
                map: map,
            });
        }
    </script>
</body>
</html>


You need to replace in the script, YOUR_API_KEY field with your own api key from google cloud console. 

  • Lets understand the code


Here, I have used a dummy location’s  latitude and longitude

We have first added an empty div with id map which will be used to load map in it. In the initMap() function, we are initializing the map, Where we are passing the parameters for our div, zoom level, and the location parameter. These 3 parameters are required to pass to load the map first. Please note that, the center parameter takes an object of location’s latitude and logitude provided in it. 

Then you will have to add the marker to the expected location and append it to the map with google.maps.Marker

  • What if I want to add a custom marker to the maps 


You can use a custom marker with you own provided image in the maps. To do that, you have to pass the icon url in the icon parameter when assigning the marker. Here is an example: 



            // URL of the custom icon
            const iconUrl = 'https://cdn-icons-png.flaticon.com/512/684/684908.png'; // Replace with your chosen icon URL

            // The marker, positioned at the specified location with custom icon
            const marker = new google.maps.Marker({
                position: location,
                map: map,
                icon: iconUrl,
            });


  • Adding custom content to the marker


If you want to add some custom content to the marker, you can do it too. This will appear as details, when user clicks on the marker and want to know more about the place, like a popup. 

We will use InfoWindow provided by maps api and use it as a onClick event listener to our marker we have generated: 




            // The content of the InfoWindow
            const infoContent = '<div style="font-size: 16px; font-weight: bold;">Custom Content</div><p>This is some custom content in the InfoWindow.</p>';

            // Create the InfoWindow
            const infoWindow = new google.maps.InfoWindow({
                content: infoContent,
            });

            // Add a click event listener to the marker to open the InfoWindow
            marker.addListener('click', () => {
                infoWindow.open(map, marker);
            });


  • Lets put all the pieces together


Here is the full code with all the customizations we have done till now: 


<!DOCTYPE html>
<html>
<head>
    <title>Google Maps with Custom Icon and Content</title>
    <style>
        /* Set the size of the map */
        #map {
            height: 100%;
            width: 100%;
        }
        /* Optional: Make the body full-height for the map */
        html, body {
            height: 100%;
            margin: 0;
            padding: 0;
        }
    </style>
</head>
<body>
    <!-- The div element for the map -->
    <div id="map"></div>

    <!-- Load the Google Maps API script -->
    <script async
        src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>

    <script>
        // Initialize and add the map
        function initMap() {
            // The location you want to center the map on
            const location = { lat: -34.397, lng: 150.644 };

            // The map, centered at the specified location
            const map = new google.maps.Map(document.getElementById("map"), {
                zoom: 8,
                center: location,
            });

            // URL of the custom icon
            const iconUrl = 'https://cdn-icons-png.flaticon.com/512/684/684908.png'; // Replace with your chosen icon URL

            // The marker, positioned at the specified location with custom icon
            const marker = new google.maps.Marker({
                position: location,
                map: map,
                icon: iconUrl,
            });

            // The content of the InfoWindow
            const infoContent = `
                <div style="font-size: 16px; font-weight: bold;">
                    Custom Content
                </div>
                <p>This is some custom content in the InfoWindow.</p>
                <a href="https://www.example.com">Visit Example</a>
            `;

            // Create the InfoWindow
            const infoWindow = new google.maps.InfoWindow({
                content: infoContent,
            });

            // Add a click event listener to the marker to open the InfoWindow
            marker.addListener('click', () => {
                infoWindow.open(map, marker);
            });
        }
    </script>
</body>
</html>

Conclusion


Using google maps via api is very customizable and handy to use. You can do plenty more changes as you need which might cover 100 of articles. Having knowledge on these maps resources will help you be comfortable and smart in integrating maps for various kind of requirements. To use Google’s extensive features and do more customizations, you will have to use it’s wide range of API services. Google provides both free and paid subscriptions to use their API. It depends on your usage or the requirement of features to decide which subscription you should go for. 

Thats all for today here. I hope you have found it helpful. Please let me know your thoughts in the comments. 

I wish you a happy day. 

Comments

Login As User
Word Count: 0