Integrate Google Maps in a Website using JavaScript

eyecatch.jpg

In the contemporary era, maps are the integral part of our lives; whether we want to find a certain location or to set our destination point of our journey, we use maps that are easily assessible not only on our mobile phones—be it Apple maps (on iPhones) or Google maps (on Android Phones) —in the form of apps, but also on web in websites. In this tutorial-based article, we are going to have a look at Google Maps for web, which you can integrate in your websites using JavaScript.

Prerequisites

In this section, we will discuss the basic components that we need in order to integrate Google Maps in our website.

Tools

I am going to use the following tools:

  • Sublime Text (you can use whatever editor you want)
  • XAMPP (Optional; for running the webpage locally)

If you want to use Sublime Text, go to the following link in order to download it:

https://www.sublimetext.com/3

Make sure to download the latest version!

Programming Language(s)

For setting up, we would require the following:

  • JavaScript (for the integration of Google Maps in the webpage)
  • HTML (front-end; for the general client end page)
  • CSS (for styles; if required)

However, our main concern in this tutorial-based article is with Google maps; hence, JavaScript is the lead actor here.

Google Maps’ API

We would need the Google Maps’ Application Programmable Interface (API) for JavaScript in order to integrate maps into our webpage. Furthermore, you would require the API key in order to use Google Maps’ service (which we will discuss in the Getting API Key section below).

Now that we have discussed all the prerequisites for this tutorial-based article, it’s time to dive into the fun part, which is developing the real application.

Scaffolding the Front End

First, we are going to make the simple HTML page, on which we would display the Google Maps. Make a new HTML file and give it any name you want. I am going to name it “front-end.html”; open it in Sublime Text and paste the following boilerplate HTML code:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Google Maps</title>
    <link rel="stylesheet" href="">
    <style>
        
    </style>
</head>
<body>
    <div id="map"></div>
</body>
</html>

Although it is an empty HTML page (if you run it in the browser), but in the above code, the following things are done:

  • Set the title of the webpage be “Google Maps”
  • Added the style in the head section in order to specify the height and the width of the Google Maps (required)
  • Added the div-tag with an id ="map" (required)

Adding Google Maps’ API Script

Now that we have the structure mentioned in HTML above, we need to now add the following Google Maps’ script at the end of the body of HTML code:

    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
    async defer></script>

There are two things that require our attention regarding the above script:

  1. YOUR_API_KEY: It must be replaced with the API KEY that we will discuss in the next section.
  2. Callback: We need to add the callback function named initMap in the script Let’s have a look at both of them!

Getting API Key

In other to get the Google Maps’ API key, you need to go to the following link and create a new project:

https://console.developers.google.com/

The project creation panel would look like the following: googlemaps_israr_1.png

  • After creating the project, go to the Dashboard and click on ENABLE APIS AND SERVICES button. Now select the “Maps JavaScript API” from the Maps section and Enable it.
  • Now go to the Credentials tab and click on the Create Credentials button; there you would be given the following options:

    1. API Key
    2. OAuth Client ID
    3. Service Account Key
  • Choose the API Key option, and you now have the API key.
  • Copy the API key and paste it in the script mentioned above in the place of YOUR_API_KEY.

Callback: initMap

After getting the API Key, we now need to add map to our webpage programmatically. Add the Script in the body of the HTML page and write the initMap function in it as follows:

<script>
        function initMap() {
            var siliconValley = {lat: 37.3875, lng:-122.0575};
            var mapOptions = {
                center: siliconValley,
                zoom: 10
            };
            var googlemap = new google.maps.Map(document.getElementById("map"), mapOptions);
        }
    </script>

In the above code, the functionality of the components is as follows:

  • mapOptions: This variable is responsible of setting the coordinates of the predefined location (which in this case is the longitude and the latitude of the Silicon Valley, CA area) and the zoom value.
  • googlemap: The new map is created by using the Google Maps’ API’s function Map and passed the above options into it. Furthermore, the id to the div HTML tag is also passed (which specifies where you want to display the map on your website). If you refresh the page now, you still won’t be able to see the map because we haven’t specified the height and the width of the map in the style tags (in head section) as specified in the scaffolding section, which is required.

Adding Dimensions of the Map

In order to specify the dimensions of the map, add the following lines of code in the style tags given in the head-section:

<style>
        #map{
            height: 500px;
            width: 100%;
        }
        
</style>

You can change the dimension (pixels) according to your need. I am using the full space of the webpage (as the width is set to 100% and height to 500px).

Now refresh the page! Wohoo! You would see the following map: googlemaps_israr_2.png

Add Marker

In order to add a marker to the map above, use the following snippet of code:

function initMap() {
            var siliconValley = {lat: 37.3875, lng:-122.0575};
            var mapOptions = {
                center: siliconValley,
                zoom: 10
            };
            var googlemap = new google.maps.Map(document.getElementById("map"), mapOptions);
            var marker = new google.maps.Marker({
                position: siliconValley,
                map: googlemap
            });
        }
  • google.maps.Marker takes two parameters: position and the map. As it can be seen above that the position is set to siliconValley and the map to googlemap.

The map with a (red) marker would look like this: googlemaps_israr_3.png

Summary

In this tutorial-based article, we have learnt how to integrate Google maps into a webpage using JavaScript. We have also learnt to add markers on top of the Google maps. I shall add more functionality to it in some other future articles, but for now, saying goodbye… I hope you like it! 😊

AUTHOR

READ NEXT

Boostlog is an online community for developers
who want to share ideas and grow each other.

Delete an article

Deleted articles are gone forever. Are you sure?