CodeinWP content is free. When you purchase through referral links on our site, we earn a commission. Learn more

Google Maps JavaScript API Tutorial: Add a Custom Map to Your Website

Google Maps helps us every day in navigating our way through roads and finding places in a manner that was unimaginative just a few decades ago. It is not only useful in wayfinding, but we also see many examples of maps used for data visualization, such as how recently many websites are using maps to visualize the spread of COVID-19 throughout the globe. Today, let’s learn how we can use the Google Maps JavaScript API to build custom maps for our websites and applications.

You might be wondering why we should dig into Google Maps JavaScript API to build maps when we can use a Static Map instead, or use one of the available WordPress plugins to do it without the hassle of coding.

Of course, both are excellent options when you want to display some business location on your website. But Google Maps JavaScript API offers you more control for times when you want to build a custom map with more complexity than a pre-built plugin has to offer.

If you do not want to spend time on coding and want a more straightforward way to display maps on your website, I recommend the Google Maps block from Otter.

Getting Google Maps JavaScript API Key

Before we start, we first need to get an API key for Google Maps. You can get it from here. The Google Maps API is not entirely free, but it comes with a free plan that is enough for most cases.

Got the API keys? Take the third exit from the roundabout and continue with the tutorial. 😉

Creating a Simple Map

A basic Google Maps instance with default settings.
A basic Google Maps instance with default settings.

First, let’s build a simple Google Map to get started. While you can separate your JavaScript and CSS, we are using a single HTML file in this tutorial. Here’s the structure we’re going to use:

<!DOCTYPE html> <html> <head> <title>Simple Map</title> <meta name="viewport" content="initial-scale=1.0"> <meta charset="utf-8"> <style> #map { height: 100%; } html, body { height: 100%; margin: 0; padding: 0; } </style> </head> <body> <div id="map"></div> <script> let map; function initMap() { map = new google.maps.Map( document.getElementById( 'map' ), { center: { lat: 51.513329, lng: -0.088950 }, zoom: 14 }); } </script> <script src="" async defer></script> </body> </html>

Once the Google Maps API loads, it calls the initMap function that initializes the map. If we break down our code even further, we use an empty div with an ID of map to declare where we want to render the map.

let map; function initMap() { map = new google.maps.Map( document.getElementById( 'map' ), { center: { lat: 51.513329, lng: -0.088950 }, zoom: 14 }); }

In our JavaScript, first, we set a map variable outside the function, so it is part of the global scope so that we can modify the map later. In our initMap function, we first declare a new Google Map and set it to render by calling the element with the ID of map. After that, we specify our options, which are the map’s center and the level of zoom.

We use the coordinates of the City of London, a historical landmark in the middle of London, as map center. Later on, we discuss how you can use Maps API to find coordinates of any location on the map. But for now, if you are curious, you can use to find coordinates of any address quickly.

Map types

Now that we have a basic map, we can look at the customization options that the Google Maps JavaScript API gives us. The first option that we are going to use is map type. Google Maps support four types of maps, which are:

  • roadmap: the default map that you usually see.
  • satellite: satellite view of Google Maps and Google Earth, when available.
  • hybrid: a mixture of roadmap and satellite view.
  • terrain: a map based on terrain information, such as mountains and valleys.

In our maps options, we can add a mapType property to select the view that we want, like this:

map = new google.maps.Map(document.getElementById( 'map' ), { center: { lat: 51.513329, lng: -0.08895 }, zoom: 14, mapTypeId: 'hybrid' });

For our example, we are using a hybrid map. You can experiment with different types to see which one suits your use case.

Map options

After map type, we come to map controls. Google Maps allows you to use any of its six controls in your maps. You can find a list of the controls on their website.

You can specify the control you want to use and its location if needed, like this:

map = new google.maps.Map(document.getElementById( 'map' ), { center: { lat: 51.513329, lng: -0.08895 }, zoom: 14, mapTypeId: 'hybrid', scaleControl: true, fullscreenControlOptions: { position: google.maps.ControlPosition.RIGHT_BOTTOM }, });

We enable scaleControl, which shows the scale of the map in the very bottom alongside Google’s copyrights, by declaring it as TRUE. And in the next line, we change the appearance of fullscreenControl from its default top-right position to bottom-right using the fullscreenControlOptions property. Similarly, you can adjust the position of other controls.

Want a control that does something other than the built-in ones? Worry not, Google Maps also allows you to create custom controls for your map.

Let’s talk about markers!

Adding a marker

Markers are amazing, and they make it possible to build lots of interactive applications with a map. For instance, some hotel booking websites use markers to show you the location of hotels on a map. And they are also very easy to add.

Let’s add a marker to the London Bridge with the following code:

let marker = new google.maps.Marker({ position: { lat: 51.506821, lng: -0.0879 }, map: map, title: 'The London Bridge' });

As you can see above, the code for our marker has three properties. The first one is the coordinates. After that, we pass the map variable where we stored our map in the beginning, and finally, we pass the title of the marker.

You can also pass the URL to a custom marker icon with an icon property in the above code block.

Adding an InfoWindow

You might find something to be missing from our markers. Usually, when you click on a marker on the map, it shows you a popup with more details. That popup is a different component in itself that is called an InfoWindow.

Google Maps with a custom marker.
Google Maps with a custom marker.

Fortunately for us, it is very easy to attach an InfoWindow to our marker.

let infoWindow = new google.maps.InfoWindow({ content: '<h2>London Bridge</h2>' }); marker.addListener( 'click', function() { map, marker ); });

First, we create a new infoWindow variable that stores our InfoWindow component. We only pass it a property of content that contains the HTML it shows once clicked. After that, we add an on-click event listener to our marker, which tells it to open the infoWindow when clicked on the marker.

Just like that, you can use a marker and an infoWindow to create interactive experiences with your map.

Now it is the right moment to pause for a second and look back at the progress that we have made. In only 30 lines of code, we have used Google Maps JavaScript API to build a custom map with markers and infoboxes. It is worth noting how easy it is to use Google Maps’ API to do things that would have seemed challenging for a beginner.

Dynamic modification & event listeners

Markers and map options are not necessarily the reasons why anyone would ditch a pre-made Google Map plugin and switch over to API. They are promising, but plenty of plugins offer these features already. Let’s try something that is not possible with a plugin.

Dynamic modification

Google Maps has many methods to interact with the map and modify its behavior. If you are used to working with DOM, then you should not have much trouble with these methods.

Some of these methods allow you to get information from the map, such as getCenter, which returns center coordinates of the map. And similarly, some allow you to change the behavior, such as setCenter, which changes the center of the map.

There are many methods, and you should take a look at all of them, so you know what is possible with the API. Let’s use one of these methods with our map.

We can add a button to our example that brings our map’s center back to the City of London.

First, we need to add a button to our code:

<button id="bringToCenter">Bring to Center</button>

Now we attach an event listener to our button that triggers the setCenter method:

const centerButton = document.querySelector( '#bringToCenter' ); centerButton.addEventListener( 'click', function( e ) { e.preventDefault(); map.setCenter({ lat: 51.513329, lng: -0.08895 }); });

And that is it. Simple, right? We have used map.setCenter in which map is the variable that we declared at the beginning to hold our map.

You should try to experiment with different methods and explore the limits of the API.

Event listeners

Another concept which JavaScript developers might be familiar with is event listeners. You can attach actions to specific events, which means that when an event happens, such as change of center, those actions get triggered.

Let’s take one of the examples from the Google Maps docs of getting the coordinates of the map when you click anywhere on it.

let infoWindowLatLang; map.addListener( 'click', function( mapsMouseEvent ) { if ( infoWindowLatLang ) infoWindowLatLang.close(); infoWindowLatLang = new google.maps.InfoWindow({ position: mapsMouseEvent.latLng }); infoWindowLatLang.setContent( mapsMouseEvent.latLng.toString() ); map ); });

As you can see, the concept is pretty much the same as how event listeners work in JavaScript. First, we attach an onClick event listener to our map. Inside our event listener, we get the coordinates of where the user clicks and put it inside an InfoWindow.

If you check the Google Map block by Otter, you can see how we use these event listeners and methods to do things such as add drag & drop of Markers and remove a marker by clicking on it.

Creating a custom control

And finally, we end this article with an example of building custom controls for your Google Maps.

As noted earlier, we are building a custom button that adds a marker to the center of the map. While the code for this looks a little complicated, it is straightforward.

First, we build a button as its function, which has an event listener to add a marker to the center of the map.

You need to replace YOUR_API_KEY in the above code block with your API key. It renders a simple Google Map with the given latitude and longitude as its center.

function MarkerControl( controlDiv, map ) { const controlUI = document.createElement( 'div' ); = '#fff'; = '2px solid #fff'; = '3px'; = '0 2px 6px rgba(0,0,0,.3)'; = 'pointer'; = '10px'; controlDiv.appendChild( controlUI ); const controlText = document.createElement( 'img' ); = '5px'; controlText.title = 'Click to add a Marker'; controlText.src = ''; controlUI.appendChild( controlText ); controlUI.addEventListener( 'click', function() { new google.maps.Marker({ position: map.getCenter(), map: map }); }); }

Most of the code above just creates an element for our button. In the very end, we attach an event listener to our button that adds a marker to the center of the map.

Now we have to attach our button to our map, which we do with the following code:

const markerControlDiv = document.createElement( 'div' ); const markerControl = new MarkerControl( markerControlDiv, map ); markerControlDiv.index = 1; map.controls[google.maps.ControlPosition.LEFT_BOTTOM].push( markerControlDiv );

The above code attaches our button to the map to its bottom left position. And that is it. That is all it takes to add custom controls to Google Maps using its JavaScript API.

Google Maps with a custom button.
Google Maps with a custom button in the bottom left corner.


A working example of everything we did in this article is available online on CodeSandbox.

That is it for this article, and I hope it gave you some confidence working with the Google Maps JavaScript API. It is incredibly straightforward to use and allows you to build pretty much anything you desire with a map!

Now you should try to use what you learned today and practice it by building a demo project for yourself using Google Maps. Let us know in the comments if you have any questions; we are happy to answer them!

Don’t forget to join our crash course on speeding up your WordPress site. With some simple fixes, you can reduce your loading time by even 50-80%:


Layout and presentation by Karol K.

Show Comments

Or start the conversation in our Facebook group for WordPress professionals. Find answers, share tips, and get help from other WordPress experts. Join now (it’s free)!