Web
Article

Google Maps Made Easy with GMaps.js

By Shivam Mamgain

Google Maps has proved to be a highly successful Google service, incorporating a range of invaluable tools such as Street View, Route Planning and Google Traffic. Many companies and organizations rely on Google Maps to provide their services – and it’s thanks to the Google Maps API that they’re able to do so.

The Google Maps API and GMaps

Google introduced the Google Maps API in 2005. This allowed developers to create custom applications with Maps. Google subsequently launched APIs for Android and iOS application development.

As useful as the Maps APIs are, they take a bit of knowhow to utilize. That’s where GMaps.js comes in. GMaps.js is an open-source, MIT-licence JavaScript library. Written by Gustavo Leon, GMaps aims to simplify the original Google Maps JavaScript API. It takes care of the extensive API code and provides appropriate methods to deal with Maps. It’s cleaner, more concise and hence easier to use.

In this article, we’ll look at map components like Markers, Polygons and Overlays. We’ll also discuss Static Maps, and the use of Geolocation and Geocoding to operate on a user’s location. All of this will be in reference to GMaps. It helps you create map applications with easy-to-use methods. I’ve used it to create a sample application (Mapit), which I’ll discuss further at the end of the article.

The Google API and GMaps Compared

The example below is from the original Documentation Page. The code (JavaScript only) loads a map with its center at latitude -34.397 and longitude 150.644, with a zoom-level of 8:

var map;
function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: -34.397, lng: 150.644},
    zoom: 8
  });
}

map is the HTML element id where the map will load.

We can write the same basic app with GMaps like this:

new GMaps({
  el: '#map',
  lat: -34.397,
  lng: 150.644,
  zoom: 8
});

This tutorial will guide you through some of the most used components in maps, with example Pens to demonstrate each.

Getting Started

Create a basic HTML page and add a reference to the Maps API. You need to include the GMaps Library too. So go to GMaps and download gmaps.js. Include it in your web page and you’re good to go.

<!doctype html>
<html>
  <head>
    <style>
      #map {
        width: 400px;
        height: 400px;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>

    <!-- Google Maps JS API -->
    <script src="https://maps.googleapis.com/maps/api/js"></script>
    <!-- GMaps Library -->
    <script src="gmaps.js"></script>
    <script>
      /* Map Object */
      var mapObj = new GMaps({
        el: '#map',
        lat: 48.857,
        lng: 2.295
      });
    </script>
  </body>
</html>

This is a rudimentary page that I’ll reference in the example snippets below. The Map Object will be modified in some of these examples.

Components

The Maps API offers various components for customizing maps. The same components can be added with GMaps with less code.

Events

A change in the HTML DOM (document object model) can be described as an event. You can call a function on the occurrence of specific events over the map (like a double-click or a mouseover). The following snippet defines functions for click and zoom_changed events:

var mapObj = new GMaps({
  el: '#map',
  lat: 48.857,
  lng: 2.295,
  click: function(e) {
    alert('You clicked on the map');
  },
  zoom_changed: function(e) {
    alert('You zoomed the map');
  }
});

You can add other events if you like. A list of all map events is provided in the Events section in the documentation. Some of the useful ones are:

Event Description
dblclick Double mouse click
mouseover Mouse enters map
mouseout Mouse exits map
drag Map is dragged
rightclick Right mouse click

Example Pen

Markers

A marker is a locator on a map. It’s generally shown as a balloon hanging over the marked location. GMaps offers the addMarker() method to add a marker. It accepts an object literal with the following properties for the marker:

  • lat: Latitude
  • lng: Longitude
  • title: Title displayed on mouseover
  • icon: Custom image for the marker
  • details: Custom object with extra data
  • infoWindow: Information about the marker

Of these, it’s mandatory to assign values to lat and lng, while the others are optional. The value of infoWindow should be another object. This object itself has the following properties:

  • content: HTML content
  • maxWidth: Maximum width for the window. If not set, window spans length of the text inside it.

infoWindow supports some more options.

This snippet is a valid example of addMarker():

var m = mapObj.addMarker({
  lat: 48.8583701,
  lng: 2.2944813,
  title: 'Eiffel Tower',
  infoWindow: {
    content: '<h4>Eiffel Tower</h4><div>Paris, France</div>',
    maxWidth: 100
  }
});

addMarker() also accepts events – for example, a marker reacting to mouseover event:

mapObj.addMarker({
  lat: 48.8583701,
  lng: 2.2944813,
  mouseover: function(e) {
    alert('Triggered');
  }
});

Example Pen

A marker can be removed using the removeMarker() method. Pass the marker object to it (m in our case) as an argument:

mapObj.removeMarker(m);

removeMarkers() collectively removes all the markers associated with the map object.

mapObj.removeMarkers();

Geocoding

To locate any point on a map, you need to have its geographical coordinates (latitude and longitude). Geocoding is calculating these geographical coordinates from a given location address. The geocode() method allows us to do the same. It takes the location address as input and processes coordinates for that address.

  • address: Location address string
  • callback: Function called after geocoding

Let’s calculate the latitude and longitude for Stonehenge, located in United Kingdom. The snippet below will calculate the geographical coordinates of the given address, and center the map at that location. If no results are found, a message is displayed:

GMaps.geocode({
  address: 'Stonehenge, United Kingdom',
  callback: function(results, status) {
    if (status == 'OK') {
      latlng = results[0].geometry.location;
      mapObj.setCenter(latlng.lat(), latlng.lng());
    } else if (status == 'ZERO_RESULTS') {
      alert('Sorry, no results found');
    }
  }
});

setCenter() method takes latitude and longitude as its parameters and centers the map at that geographical location. It also accepts an optional callback parameter, a function triggered after the map is centered.

There are two parameters in the callback function: results and status.

results is an object array, storing the locations of all the places with the defined address. Since there can be more than one place with the same name, there can be more than one result. results stores each one of them. The location of the ith result can be determined using results[i].geometry.location.

If no results were found for an address, status stores ZERO_RESULTS, else OK.

Example Pen

Geolocation

Geolocation calculates the user’s current geographical position. The geolocate() method lets us exploit this feature. It accepts an object literal with four properties, of which always is optional and the others all required. Each property is defined as a function that’s executed in specific cases:

  • success: Geolocation was successful
  • error: Geolocation was not successful
  • not_supported: Browser does not support geolocation
  • always: Executed in every case
GMaps.geolocate({
  success: function(position) {
    mapObj.setCenter(position.coords.latitude, position.coords.longitude);
  },
  error: function(error) {
    alert('Geolocation failed: ' + error.message);
  },
  not_supported: function() {
    alert("Your browser does not support geolocation");
  },
  always: function() {
    alert("Always");
  }
});

Example Pen

Polylines

Polylines help to trace a path on a map. A path can be formed by joining coordinates of different points. The drawPolyline() method draws a polyline for a path. This path is provided as an array of coordinates (latitude and longitude). Apart from path, you can specify other properties for a polyline. Some of them are:

  • strokeWeight
  • strokeColor
  • strokeOpacity

All three define the style for the polyline. There are others as well, although we won’t be covering them in this article.

var path = [
  [-12.044012922866312, -77.02470665341184],
  [-12.05449279282314, -77.03024273281858],
  [-12.055122327623378, -77.03039293652341],
  [-12.075917129727586, -77.02764635449216],
  [-12.07635776902266, -77.02792530422971],
  [-12.076819390363665, -77.02893381481931],
  [-12.088527520066453, -77.0241058385925]
];

var pl = mapObj.drawPolyline({
  path: path,
  strokeColor: '#76ff03',
  strokeOpacity: 1,
  strokeWeight: 10
});

Example Pen

A polyline can be removed using the removePolyline() method. It takes the polyline object as its parameter. Remove pl polyine using:

mapObj.removePolyline(pl);

removePolylines() removes all the polylines associated with a map object.

mapObj.removePolylines();

Polygons

drawPolygon() helps you create a polygon on a map. Pretty much like the drawPolyline() method, you need to define a paths property. The stroke style properties (strokeWeight, strokeColor and strokeOpacity) work of polygon as well. They define the border of the polygon. Besides these, you can specify the fill color and opacity for the polygon:

  • fillColor
  • fillOpacity

Other polygon options can be found in the documentation.

var path = [
  [-12.040397656836609, -77.03373871559225],
  [-12.040248585302038, -77.03993927003302],
  [-12.050047116528843, -77.02448169303511],
  [-12.044804866577001, -77.02154422636042]
];

var pg = mapObj.drawPolygon({
  paths: path,
  strokeColor: '#000000',
  strokeOpacity: 0.3,
  strokeWeight: 2,
  fillColor: '#00e676',
  fillOpacity: 0.4
});

Remember: It’s the path property for drawPolyline() and paths property for drawPolygon().

Example Pen

To remove the polygon pg, use:

mapObj.removePolygon(pg);

Remove all polygons defined in mapObj:

mapObj.removePolygons();

Circles

Creating circular shapes with drawPolygon() is not viable. drawCircle() helps you with that. Its parameter list includes:

  • lat: Latitude for center
  • lng: Longitude for center
  • radius: Radius in meters on Earth’s surface.

Other options include styles for stroke and fill of shape (same as polygon), and some more.

var c = mapObj.drawCircle({
  lat: 51.178875,
  lng: -1.826259,
  radius: 300,
  fillColor: 'yellow',
  fillOpacity: 0.5,
  strokeWeight: 0,
  click: function(e){
    alert('You are inside 300m radius of Stonehenge')
  }
});

Example Pen

Overlays

An overlay is a layer over the map with HTML content on it. GMaps supports overlays with the drawOverlay() method. It accepts the following hash:

  • lat: Latitude
  • lng: Longitude
  • content: HTML content
  • verticalAlign: top, middle, bottom
  • horizontalAlgin: left, middle, right
  • verticalOffset
  • horizontalOffset

The alignments and offsets are with respect to the point defined by lat and lng.

Example snippet:

var ol = mapObj.drawOverlay({
  lat: 27.1733151,
  lng: 78.0409684,
  content: '<div class="overlay">Taj Mahal</div>',
  verticalAlign: 'top',
  horizontalOffset: -40
});

You can define CSS styles for the content. In our example, we have defined the overlay class.

.overlay {
  border: 1px solid #b71c1c;
  background: #d50000;
  padding: 5px;
  font-size: 17px;
  color: white;
}

Example Pen

Remove overlay? Well, you know it:

mapObj.removeOverlay(ol);

Remove all overlays for a map object? You know that as well:

mapObj.removeOverlays();

Static Maps

A static map is an image of the map, which can independently be embedded into websites. GMaps lets you generate a URL to a static map. This URL can then be added as source to an image.

staticMapURL() generates the required map URL after taking the following parameters:

  • size: An array of width and height in pixels
  • lat
  • lng
  • zoom

Code snippet:

url = GMaps.staticMapURL({
  size: [500, 500],
  lat: 51.178882,
  lng: -1.8284037,
  zoom: 16
});

Example Pen

In our example, we have created an img element and added the URL to its src:

var map = document.getElementById('map');
var static_img = document.createElement('img');
static_img.src = url;
map.appendChild(static_img);

We can apply markers and polylines to static maps too.

Example Pen

Sample Application (Mapit)

Mapit (view source on GitHub) creates a static map for a route between source and destination. Zoom down to an address on the map and place two markers (a source and a destination). Mapit will trace a route from one marker to another. It will create a url to the static map with the current configuration. You can preview the static map and download the image.

Conclusion

This article covers basic components of Maps. I’m sure it has served as a good getting-started guide to GMaps and interactive map applications. But it shouldn’t stop here. There is a lot more you can do with GMapsjs.

Have you used GMaps yet? If so, what has been your experience. If you have any comments or questions, please join the discussion below.

More:
  • http://www.dfbgaming.com/ {dFb}eMac

    Interesting. It would be nice if this library had support for custom panoramas but it covers most of the cases I’d need. Thanks for this.

  • http://hpneo.github.io/ Gustavo Leon

    Thanks for writing about GMaps.js and create such an amazing tutorial (it’s already in the repo’s wiki). I will try to answer any question or issue you guys post in the repo’s issues tracker. Also, any contribution is welcomed :)

  • http://www.dfbgaming.com/ {dFb}eMac

    Sorry for the late reply! I’ll see if I can dig up some panoramas and open an issue for you.

  • psrwkeith

    Excellent plugin. Is there a way to colour maps – for example I want the map to be black and white? Thanks

  • david lopes

    Great Tutorial, How can I make my map full-size and responsive?

  • http://www.aasoftwares.net Joseph Mutai

    The Geolocation does not work. put a place like ‘Langata Shopping Centre, Nairobi’ and you will get somewhere West east (Ushirika Road). Even the sample file:///D:/wamp/www/GoogleCodes/gmaps-autocomplete-master/index.html or Gmap geolocation example.

    • http://www.aasoftwares.net Joseph Mutai

      realised its google geocoder that has the problem. Its never accurate.

  • Ioannis Michelakos

    could you please help me on how to consume this great libray on an Angular 2 app?

  • http://skytechgeek.com Gagan Chhatwal

    Amazing stuff, I love the way you write about Gmap.js and informative tutorial, I got some good jQuery Map Plugins here…
    http://gojquery.com/jquery-map-plugins/

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Instant Website Review

Use Woorank to analyze and optimize your website to improve your website to improve your ranking!

Run a review to see how your site can improve across 70+ metrics!

Get the latest in Front-end, once a week, for free.