Google Maps and Markers 101

Filed under: API
Written By: Walter G.
Published On:

There is no better way to share a location than with a map and a marker on it. The universal indicator of map based location in this and age. So today let's go over how to generate a map on your website using the Google Map JavaScript API, and how to add markers wherever you wish to mark your place.

A few more advanced features, like clearing the markers and adding click events to the markers will be covered as well down below.

Overview

At the end of this post, you should be able to handle the following on your Google maps.

  • Render a map (based on coordinates)
  • Create a marker
  • Delete a marker
  • Show an informational box on marker click

Get an API key

Before you can start to play around with the Google Maps functionality, you will need to get your hands on your very own Google API Key, which you can get from the following URL.

Requests to the Google Maps API are rate limited. However, more than likely, you will not run out of requests using the free tier. But if you're going to be implementing this on a high traffic website, then perhaps you should take that into account.

Render the map

Rendering a Google map isn't as straightforward as one may think, at least not from a development point of view. It's more than just iframe, as many would like to believe.

So start things off, let's add a div element to our webpages where our maps will reside.


<div id='gmap_canvas' class="sl-map__canvas" style='height:250px;width:100%;'></div>

Now you will need to load the Google Maps JavaScript API to your page and you can do that with the following, which you can add just before the closing </body> tag:


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

The callback function in the URL will get called once the API has finished loading onto the page. So you will need to define that somewhere where you place your scripts.


    function initMap() {
        var mapOptions = {
            mapTypeId: 'roadmap',
            zoom: 9,
            zoomControl: true,
            scaleControl: true,
            center: {lat: -34.397, lng: 150.644}
        };

        map = new google.maps.Map(document.getElementById("gmap_canvas"), mapOptions);       
}

This is enough to renter a map on your website. For a list of all of the mapOptions that you can set, check out the following reference guide. But the important notes here are that this function will get called by the API when it is ready, that we are defining mapOptions, and that we are instantiating a google maps object passing in our canvas and the map options.

Adding a marker

The map is great, but not much use without a marker specifying something. The Google Maps API makes it relatively simple to add a marker to the map. You will essentially need to declare a marker object with the appropriate properties, and set it's map property, to the map object that we declared above in the initMap function.


     // call this anytime after the initMap function
     function loadMarkers()
     {
     	var position = new google.maps.LatLng(-34.397, 150.644);
     	var marker;
        var clickIcon = {
                    path: 'M-20,0a20,20 0 1,0 40,0a20,20 0 1,0 -40,0',
                    fillColor: '#fd4848',
                    fillOpacity: 1,
                    strokeColor: 'white',
                    strokeWeight: 2,
                    scale: .5
                };

                marker = new google.maps.Marker({
                    position: position,
                    map: map,
                    title: 'hello world',
                    icon: clickIcon
                });
    }

This marker will use an SVG Path to generate a circle icon. Google Maps is flexible enough to allow for SVG or images as icons. We're also declaring a LatLng object and setting the latitude and longitude accordingly. The magic happens in the marker instantiation. We pass in both the position object we declared, the map object, which gets set in the initMap function and setting the icon to the SVG object that we defined.

Marker clicks

Clicking the icon by default produces no visible results. We'll have to attach a click event to the marker object when we are defining it.


    var infoWindow = new google.maps.InfoWindow();

    marker = new google.maps.Marker({
        position: position,
        map: map,
        title: 'hello world',
        icon: clickIcon
    });

     google.maps.event.addListener(marker, 'click', (function (marker, i) {
         return function () {
             infoWindow.setContent('hello world');
             infoWindow.open(map, marker);
         }
         })(marker, i));

There are numerous events that you can trigger an event on, such as dragging the map and zooming in and out, and they all follow the same pattern as the click function above. The content of the functions is broken down further down below.

Adding an infowindow

For the most part, you'll want an icon click to show something. And while you can indeed do whatever you want after a marker click, such as generating a modal window in JavaScript, you also have the option to use the Google Maps built in InfoWindow object, which you saw in the above snippet of code.

And again, this gets generated when we're creating our marker object. We'll need to define an infoWindow object before we can set it. However once defined, we can set its content, which can be either text or HTML and we can call its open function to display it.


    infoWindow.setContent('hello world');
    infoWindow.open(map, marker);

And there you have it. A fully functional map with marker and info window features. This example isn't very practical, as hardcoded markers probably aren't going to be used in your project. But it should give a fairly good idea as to how the Google Maps API functions.

The Google Maps JavaScript API is a very powerful and flexible way to show interactive geographical data. This covers the basic steps towards generating a usable map, but you can dive much deeper into the API and implement many cooler functions. You can add legends, handle zoom events, panning events, and even add your own overlays to the map layout.

Comments