Google Maps Made Easy with GMaps.js

Share this article

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.

Frequently Asked Questions (FAQs) about Google Maps with Gmaps.js

How can I get started with Gmaps.js?

To get started with Gmaps.js, you first need to include the Google Maps JavaScript API in your HTML file. After that, include the Gmaps.js library. You can download it from the official GitHub repository or use a CDN. Once you’ve included these scripts, you can initialize a new map by creating a new GMaps object and passing in the id of the HTML element where you want the map to be displayed, along with some options like the latitude and longitude of the center of the map.

What are the key features of Gmaps.js?

Gmaps.js simplifies the process of working with Google Maps. It provides a simple and intuitive API for creating and manipulating maps. Key features include the ability to easily add markers, polygons, and layers, geolocation, geocoding, and more. It also supports events, allowing you to respond to user interactions such as clicks or drags.

How can I add markers to a map using Gmaps.js?

Adding markers to a map with Gmaps.js is straightforward. You can use the addMarker method on your GMaps object, passing in an object with the latitude and longitude of the marker. You can also include other options like the title, click events, and more.

How can I use geolocation with Gmaps.js?

Gmaps.js provides a getGeolocation method that you can use to get the user’s current location. This method returns a promise that resolves with the user’s latitude and longitude. You can then use this information to center the map on the user’s location or add a marker at their location.

How can I use geocoding with Gmaps.js?

Geocoding is the process of converting addresses into geographic coordinates, which you can use to place markers or position the map. Gmaps.js provides a geocode method that takes an address and returns a promise that resolves with the geocoded result.

How can I add events to a map with Gmaps.js?

Gmaps.js supports a variety of events, including click, drag, zoom_changed, and more. You can add an event listener to your GMaps object using the addListener method, passing in the event name and a callback function to be executed when the event occurs.

How can I add layers to a map with Gmaps.js?

Gmaps.js supports adding various types of layers to a map, including traffic, transit, and bicycle layers. You can add a layer using the addLayer method on your GMaps object, passing in the name of the layer.

How can I draw shapes on a map with Gmaps.js?

Gmaps.js provides methods for drawing various shapes on a map, including lines, polygons, circles, and rectangles. You can use the drawOverlay, drawPolygon, drawCircle, and drawRectangle methods on your GMaps object.

How can I customize the appearance of a map with Gmaps.js?

Gmaps.js allows you to customize the appearance of a map using styles. You can pass in a styles option when creating your GMaps object, which should be an array of style objects that describe how different elements of the map should be styled.

How can I handle errors with Gmaps.js?

Gmaps.js provides a way to handle errors that occur when using the library. You can listen for the ‘error’ event on your GMaps object, which will be triggered whenever an error occurs. The event object will contain information about the error, including a message and a stack trace.

Shivam MamgainShivam Mamgain
View Author

Shivam is an Open-source Software Developer with a keen interest in Web Development and Competitive Programming. A Python Zealot, casual gamer and a(n infrequent) blogger.

apimapsRalphM
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week