How to Add Google Maps to a Website ?
The purpose of this article is to add Google Maps to a website. These are the following steps to add Google Maps to a website.
- Generate an API Key
- Create the HTML Container of the map
- Add an external script by google inside the HTML document
1. Generate an API Key
To fetch the location data from google maps at 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:
- Visit the Google Map section of Google Cloud Console.
- Go to the credentials section of the menu on the left side-bar.
- Click on the ‘Create Credentials’ button below the navigation bar.
- Select ‘API KEY’ to generate a new API KEY.
- Copy the key and save it for future use.
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:
- Create a new HTML document.
- Inside the body section create an empty div, and give it a specific ID for styling purpose. In our example the specific ID given is ‘map’ as it is going to contain the map.
- Create a style tag and set the size of the div.
3. 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.
- Initialize a function named initMap(). The name cannot be changed as this function name is the prebuilt indicator by Google which initializes and adds the map when the webpage loads.
- Inside that function initialize an object that contains the latitude and the longitude of the location that we are willing to show in the map.
- Create a new google.maps.Map object which takes the container element, the object which stores the center location and the zoom of the map.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.