DEV Community

Cover image for Google Maps: Show multiple markers and add your event on click
Rémy Beumier
Rémy Beumier

Posted on • Updated on

Google Maps: Show multiple markers and add your event on click

I recently had a request to integrate Google Maps into a website. I thought It would be fairly straightforward as I integrated some maps before and it was all about an iframe. However going through the requirements, I discovered it wouldn't be that simple.

The map request had 3 main points:

  • Show the different firm offices on a map
  • Be sober and follow firm's brand guidelines
  • Show custom information when clicking on an office

Searching for possibilities I quickly came across the Google Maps API. It is of course more complex than the iframe I was used to but it is also a far more flexible tool!

Note: a dev version of the map will wait for you at the end of the article.

1. Initialize the map

First, I had to get the map rendering on my page. To initialize the map, you need to work with basic HTML, a bit of CSS and JavaScript as Google shows you.

In HTML we create a div that we will later point to in the script and we add the Google Maps API link with a callback function. In the most basic way, it would look like this.

<div id="map-canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=&callback=initMap"></script>
Enter fullscreen mode Exit fullscreen mode

In CSS we need to define a certain height to the #map-canvas element. Of course it would look better with more styling, but let's keep to the basics at the moment.

#map-canvas {
  height: 400px;
}
Enter fullscreen mode Exit fullscreen mode

In JavaScript we create a function that will initialize the map. In this example we defined the center as the center of Belgium and the zoom to 7. It is up to you to define other values to show any place in the world.

var map;
function initMap() {
  map = new google.maps.Map(document.getElementById('map-canvas'), {
    center: {lat: 50.641111, lng: 4.668056},
    zoom: 7
  });
}
Enter fullscreen mode Exit fullscreen mode

2. Make the map responsive

Of course the map had to be responsive for the client. As I often have to make videos responsive I used the same technique. The technique relies on padding of a parent div set to a certain ratio.

Actually, this trick works for all iframe; Youtube as well!

<div class="container">
  <div id="map-container">
    <div id="map-canvas"></div>
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode
.container {
  position: relative;
  width: 100%;
  max-width: 600px;
  margin: auto;
}

#map-container {
  padding: 56.25% 0 0 0;
  height: 0;
  position: relative;
  }

#map-canvas {
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  width: 100%;
}
Enter fullscreen mode Exit fullscreen mode

3. Make the map zoom responsive

I had my map container behaving responsively but I had issues with the zoom of the map. Indeed the map could become too small for its content. Here is how I fixed it.

We create a variable responsiveZoom that checks the window size and give a zoom level accordingly. We add an event listener on window resize that zooms in or out on certain breaking points.

var responsiveZoom = (window.innerWidth < 768) ? 6.75 : 7.75;

window.addEventListener("resize", function() {
  if (window.innerWidth < 768) responsiveZoom = 6.75
  else if (window.innerWidth > 768) responsiveZoom = 7.75
  map.setZoom(responsiveZoom);
});
Enter fullscreen mode Exit fullscreen mode

4. Create new markers

Next, I figured out how to add my own markers on the map.

We need to add the different markers corresponding to the different offices. Let's pick some random point for the example and here is how to proceed if we don't know latitude and longitude values:

  1. Search Google Maps for our place, or set our marker anywhere.
  2. Right-click on the marker and select "More info on this place".
  3. Copy the latitude and longitude values

And here is how to add the markers in the code.

// inside mapInit function
var markerGrandPlace = new google.maps.Marker({
  position: new google.maps.LatLng(50.846759, 4.352446),
  map: map,
  title: "Brussels Grand-Place"
});
Enter fullscreen mode Exit fullscreen mode

5. Create new events

On the custom markers, I had to add an event listener to zoom in the map and to display specific information about the office.
Here is how we can add such event.

// inside mapInit function
google.maps.event.addListener(markerGrandPlace, "click", function() {
  map.panTo(this.getPosition());
  map.setZoom(20);
});
Enter fullscreen mode Exit fullscreen mode

It handles the zooming and we can add any code we want in order to show other piece of information. We won't cover that, there is one approach in the Codepen solution below.

6. Style your map

Remember the map had to follow some styling guidelines? Well Google Maps has this covered with an helpful tool: the Styling Wizard.

We can play around with the tool and get the desired level of info shown, the right colors, fonts etc.

If we want to change the markers icons, Google has a small collection of colors but we can use any image of course.

// inside mapInit function
var markerGrandPlace = new google.maps.Marker({
  position: new google.maps.LatLng(50.846759, 4.352446),
  map: map,
  title: "Brussels Grand-Place",
  icon: "http://maps.google.com/mapfiles/ms/icons/blue-dot.png"
});
Enter fullscreen mode Exit fullscreen mode

7. Get your API key

In order to benefit from all these tools, I needed to get an API key from Google. Indeed the API is not free and given the quality of the service, it makes total sense.

We will need to create a billing account by clicking on get started and following the steps.
Once we have it, we can paste it in our call to the Google Maps API.

// replace 'YOUR_API_KEY' with your actual key
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
    async defer></script>
Enter fullscreen mode Exit fullscreen mode

8. Restrict your key

The last step we need to pay attention to is the restriction of our key. We will be able to do it at the end of our key registration. It adds some protection to our API key by specifying where it could be used: A website, an app or a specific URL.

Live example on Codepen

Isn't an example worth a million words? 😄

Hopefully, this article will have teach you some about Google Maps API or helped you creating out-of-the-box maps.

Keep playing to learn! 🔥

If you find value in what I offer don't hesitate and buy me a coffee 😇

Note: I am sharing a specific case that you could reproduce or get inspired from. If you want more info about the Google Maps API and its possibilities, go for it!

Discussion (0)