Skip to main content

Add a Custom Map to Your Website

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 latlong.net 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() { infoWindow.open( 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() ); infoWindowLatLang.open( 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.

Wp-dd.com

WordPress Design, WordPress Development, cPanel Hosting, Web Design, Web Development, Graphic Design, Mobile Development, Search Engine Optimization (SEO) and more.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.