Walkthrough Using the Google Maps JavaScript API

Getting Started With Google Maps Javascript API

Posted in

Google Maps API is a popular, powerful tool for creating custom maps that are also searchable, displaying live location data, planning routes, or syncing up with other APIs. It’s little wonder the Google Maps API is regularly one of the most popular APIs on API directories like RapidAPI.

The Google Maps API is also a good API to practice programming with. It’s easy to work with. It’s useful and versatile. And it’s free, provided you don’t go over your quota.

With that in mind, we’ll show you how to build a custom map project using the Google Maps JavaScript API. By the time you’re done, you’ll know how to set up a Google Cloud account for your Google Maps project, enable APIs in Google, get an API key, and then build your first Google Map using the Google Map API.

Getting Started with Google Maps JavaScript API

Step 1. Create a Google Cloud Project

To start, we’re going to create a project in Google Cloud, which is required if you want to use the Google Maps platform. This allows you to set up billing, manage services, and enable APIs and SDKs.

First, create a Google Cloud project using the Cloud Console and then enable billing. Keep in mind your project won’t be charged unless you exceed the no-charge quota.

On the project page, you can give your project a custom name and ID. We named ours HeadInTheCloud, but feel free to use the default. We left the location as default as well since we don’t have organizations to link to yet.

Now you need to enable billing. If you already have a billing account associated with your Google Cloud account, it will automatically link to your new project. Otherwise, you will be prompted to create a billing account. There is no limit on how much you might be charged, so you might want to create a budget or set an alert.

Next, you’re going to enable the Google Maps JavaScript API.

Once you’ve activated your API key and set an alert, you’ll be able to see a list of all of your projects and APIs on the Google Maps Platform Page.

Once you’re finished testing out the Google Maps platform, you can shut down your cloud project by selecting your Cloud project and choosing Delete.

Step 2. Using Google Maps JavaScript API Keys

You should’ve been given an API key when you created your Google Cloud project. If not, you can create a new one to ensure your Google Maps JavaScript API remains secure.

Start by selecting your project in the Select A Recent Project section. Then select Create Credentials next to the All Google Maps Platform APIs dropdown menu. Select API Key from the options.

Next, we’re going to restrict the API keys to only the APIs needed for your application, which Google recommends as a best practice for API security.

Start by selecting the API key you want to restrict. You can restrict which applications and websites can access your API. You can use to accept all calls from a particular domain. .google.com would accept all API calls from Google.com, for example.

Under API restrictions, you can choose which APIs your API key can be used for. Select Google Map JavaScript API from the dropdown menu and select OK. You can select Places API if your project calls for it, as well. Finally, select Save.

When you’re done, you can insert your API key into this code snippet:

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

Step 3. Adding a Marker to a Google Map

Now we’re going to create a simple HTML web page, populate it with a Google Map, and then place a marker on it.

To start, here’s code for a simple, barebones HTML webpage:

<!DOCTYPE html>
<!--
 @license
 Copyright 2019 Google LLC. All Rights Reserved.
 SPDX-License-Identifier: Apache-2.0
-->
<html>
  <head>
    <title>Add Map</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>

    <link rel="stylesheet" type="text/css" href="./style.css" />
    <script type="module" src="./index.js"></script>
  </head>
  <body>
    <h3>My Google Maps Demo</h3>
    <!--The div element for the map -->
    <div id="map"></div>

    <!-- 
      The `defer` attribute causes the callback to execute after the full HTML
      document has been parsed. For non-blocking uses, avoiding race conditions,
      and consistent behavior across browsers, consider loading using Promises
      with https://www.npmjs.com/package/@googlemaps/js-api-loader.
      -->
    <script
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&v=weekly"
      defer
    ></script>
  </body>
</html>

This is a simple skeleton with a simple H3 tag titled “My Google Maps Demo” and a single

element. If you’re familiar with HTML and want to experiment, feel free to modify the HTML code to your heart’s content.

If you don’t have a web domain to host HTML files, you can run the test code using Stackblitz or CodeSandbox.io.

Next, we’re going to add a map with a marker using the following code:

// Initialize and add the map
function initMap() {
  // The location of Uluru
  const uluru = { lat: -25.344, lng: 131.031 };
  // The map, centered at Uluru
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 4,
    center: uluru,
  });
  // The marker, positioned at Uluru
  const marker = new google.maps.Marker({
    position: uluru,
    map: map,
  });
}

window.initMap = initMap;

As before, you can test the code using StackBlitz, CodeSandbox.io, or JSFiddle.

In this code, a function is created to call the map, called initMap(). A constant named uluru is created and associated with a specific latitude and longitude using const uluru = { lat: -25.344, lng: 131.031 };.

It also specifies where the map is centered, in this case on uluru, and the zoom variable specifies the amount of zoom for your map, with Zoom 0 being the entire Earth.

That’s all there is to it! Once you’ve got the basics down, you can further customize your markers using animations or vector-based icons.

You can also customize your map or draw on it directly.

You can further customize your map by adding your own markers wherever you want, but you’ll need to convert the location using geocoding.

Final Thoughts on Getting Started With Google Maps JavaScript API

As you can see, it’s not hard to get up and running with the Google Maps JavaScript API. Of course, this is just a rudimentary example to get you started. Adding each marker to a Google Map by hand will have limited usefulness, but if you’re familiar with programming, you can experiment with populating your map using variables.

There are so many potential applications for creating your own custom maps using the Google Maps JavaScript API. You could use it to create a boilerplate for adding a location map to a website. You could allow multiple contributors and create a collaborative trip-planning app. Or, you could use the Google Maps JavaScript to locate historical trends across time and space.

To summarize, we’ve shown you how to create a Google Cloud account and associate it with a Google Maps API. We then showed you how to create an API key and restrict access solely to the Google Maps API. Finally, we showed you how to create a custom Google Map and then add a marker using the Google JavaScript API.