HTML5 Zone is brought to you in partnership with:

Paulund is a website dedicated to writing tutorials and code snippets about Web Development, the main subjects are PHP, Wordpress, jQuery, CSS3 and HTML5. Paul is a DZone MVB and is not an employee of DZone and has posted 134 posts at DZone. You can read more from them at their website. View Full User Profile

Create Google Maps With gmaps.js

12.15.2012
| 15550 views |
  • submit to reddit

gmaps.js

How To Use GMaps.js

GMaps is a javascript plugin that makes it really easy to use GoogleMaps to display a map to your user. There are multiple options that make it easy to add pointers to the map, directions, information boxes and lots more.

This plugin is massive there is loads of options to go through, in this tutorial I'm not going to go through all of them. I'm just going to go through the options which will be the ones you are most likely going to use.

If you want to see all the options for this plugin you can view the documentation on the Github Repository.

Documentation

To start using GMap.js you need to download the latest version from Github.

Download GMap

Once you have the latest now include the Javascript file and jQuery on your page inside your

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script src="gmaps.js"></script>
</head>
<body>
</body>
</html>

When adding the gmap.js to the page it will create a Javascript object called GMaps which you will use to create your maps.
$(document).ready(function(){
 var map = new GMaps({
    el: '#map',
    lat: 51.5073346,
    lng: -0.1276831,
  });
});

Basic Map

In this example it's just going to be a basic map inside a div. This is the easiest way of using GMaps.js all you need is a bit of Javascript and a div on the page.

First we add the GMap Javascript file to the page like above and create a HTML div.

<div id="basic_map"></div>

Now we can create the Javascript to add a basic map to the page, for this map we are going to set the center of the map to show London.

We can assign different options to include zoom controls, street view, overlay settings etc.

/**
  * Basic Map
  */
$(document).ready(function(){
 var map = new GMaps({
    el: '#basic_map',
    lat: 51.5073346,
    lng: -0.1276831,
    zoom: 12,
    zoomControl : true,
    zoomControlOpt: {
        style : 'SMALL',
        position: 'TOP_LEFT'
    },
    panControl : false,
  });
});

Basic Map Demo

Mouse Events On The Map

Having your map response to user interaction can be really useful in most applications, this is why the GMap.js has included different mouse events for your map. In this example we are going to use the click event and the drag event to display an alert on the screen.

Again the HTML is very simple.

<div id="mouse_event_map"></div>

For this we can use the same map as above but have different options for click and dragend events. We can then assign a function to run on these different events.

/**
 * Mouse Events on Maps
 */
$(document).ready(function(){
 var map = new GMaps({
    el: '#mouse_event_map',
    lat: 51.5073346,
    lng: -0.1276831,
    zoom: 12,
    zoomControl : true,
    zoomControlOpt: {
        style : 'SMALL',
        position: 'TOP_LEFT'
    },
    panControl : false,
    click: function(e){
      alert('Click event');
    },
    dragend: function(e){
      alert('Drag Event');
    }
  });
});

mouse_event

Mouse Events Demo

Create Map Pointer With Information

The next feature we are going to look at is the ability to add pointers to your marker at exact longitude and latitude.

With GMap it makes this functionality very simple, you can also create a HTML information box to appear when you click the markers.

The HTML again is just a div with an ID.

<div id="pointers_map"></div>

For this example I am using some of London's biggest attractions as pointers for the map.

Adding a pointer is as easy as using the method addMarker().

map.addMarker({
        lat: 51.5007396,
        lng: -0.1245299,
        title: 'Big Ben',
        infoWindow: {
          content: '
Big Ben is the nickname for the great bell of the clock at the north end of the Palace of Westminster in London, and often extended to refer to the clock and the clock tower, officially named Elizabeth Tower.
'
        }
      });

We use this method on the object that is returned from the GMap class.

/**
 * Map Pointers
 */
$(document).ready(function(){
 var map = new GMaps({
    el: '#pointers_map',
    lat: 51.5073346,
    lng: -0.1276831,
    zoom: 13,
    zoomControl : true,
    zoomControlOpt: {
        style : 'SMALL',
        position: 'TOP_LEFT'
    },
    panControl : false,
  });
map.addMarker({
      lat: 51.503324,
      lng: -0.119543,
      title: 'London Eye',
      infoWindow: {
        content: '
The London Eye is a giant Ferris wheel situated on the banks of the River Thames in London, England. The entire structure is 135 metres (443 ft) tall and the wheel has a diameter of 120 metres (394 ft).
' }
    });
    map.addMarker({
      lat: 51.5007396,
      lng: -0.1245299,
      title: 'Big Ben',
      infoWindow: {
        content: '
Big Ben is the nickname for the great bell of the clock at the north end of the Palace of Westminster in London, and often extended to refer to the clock and the clock tower, officially named Elizabeth Tower.
'
      }
    });
    map.addMarker({
      lat: 51.518856,
      lng: -0.1263371,
      title: 'British Museum',
      infoWindow: {
        content: '
The British Museum is a museum in London dedicated to human history and culture.
'
      }
    });
    map.addMarker({
      lat: 51.5085822,
      lng: -0.1283169,
      title: 'National Gallery',
      infoWindow: {
        content: '
The National Gallery is an art museum on Trafalgar Square, London. Founded in 1824, it houses a collection of over 2,300 paintings dating from the mid-13th century to 1900.
'
      }
    });
    map.addMarker({
      lat: 51.5228316,
      lng: -0.1553503,
      title: 'Madame Tussauds',
      infoWindow: {
        content: '
Madame Tussauds is a wax museum in London with branches in a number of major cities.
'
      }
    });
    map.addMarker({
      lat: 51.5089465,
      lng: -0.0764269,
      title: 'Tower Of London',
      infoWindow: {
        content: '
Her Majesty\'s Royal Palace and Fortress, more commonly known as the Tower of London, is a historic castle on the north bank of the River Thames in central London, England, United Kingdom.
'
      }
    });

This will create a Google map that looks like this.

pointer_google_maps

Map Pointers Demo

Using GeoLocation

Geolocation will allow your browser to locate your exact longitude and latitude, this is really useful for maps on mobile devices. If your asking for directions from a mobile device you are more than likely going to ask for directions from your current location.

With GMap.js we can easily use another property on the object to get your location and place a marker in your exact location.

First create your map div.

<div id="geolocation_map"></div>

Use the below Javascript to create a marker in your current location. This uses a method on the GMaps object called geolocate().

/**
 * Geolocation
 */
 var map;
$(document).ready(function(){
  var map = new GMaps({
    el: '#geolocation_map',
    lat: 51.5073346,
  lng: -0.1276831,
  });
  GMaps.geolocate({
    success: function(position){
      map.setCenter(position.coords.latitude, position.coords.longitude);
      map.addMarker({
        lat: position.coords.latitude,
        lng: position.coords.longitude,
        title: 'You are here.',
        infoWindow: {
          content: '
You are here!
'
        }
      });
    },
    error: function(error){
      alert('Geolocation failed: '+error.message);
    },
    not_supported: function(){
      alert("Your browser does not support geolocation");
    }
  });
});

Geolocation Map Demo

Directions

In the previous example of Geolocation I spoke about how using Geolocation is really useful for people to use with directions so you can get directions from your current location.

Using GMaps.js getting the Geolocation and drawing the direction route are both very easy. First we use the geolocate method to get the user current position then, we use the drawRoute method to draw the route from your current position to the destination.

/**
 * Directions to London
 */
var map;
$(document).ready(function(){
  var map = new GMaps({
    el: '#directions_map',
    lat: 51.5073346,
    lng: -0.1276831,
    zoom:8
  });
  GMaps.geolocate({
    success: function(position){
      map.setCenter(position.coords.latitude, position.coords.longitude);
       map.drawRoute({
        origin: [position.coords.latitude, position.coords.longitude],
        destination: [51.5073346, -0.1276831],
        travelMode: 'driving',
        strokeColor: '#000',
        strokeOpacity: 0.6,
        strokeWeight: 6
      });
    },
    error: function(error){
      alert('Geolocation failed: '+error.message);
    },
    not_supported: function(){
      alert("Your browser does not support geolocation");
    }
  });
});

Cardiff To London

Directions Map Demo

Static Maps

Sometimes when you display a map on a page you don't want the user to have any interaction with it, you just want to display an image of a location.

With GMaps.js you can make the plugin display an image of any location.

You can set the size of the image you want to use and the location, just provide it with a div placeholder and that's it.

/**
 * Static Maps
 */
$(document).ready(function(){
  var url = GMaps.staticMapURL({
    size: [610, 350],
    lat: -33.858290691930996,
    lng: 151.21517658233643
  });
  $('<img/>').attr('src', url).appendTo('#static_map');
});

Static Map Demo

Conclusion

As you can see from this example code it's really easy to use GMap on your pages. These are just a few examples of how to use the GMap.js plugin, examples of using all options on the plugin can be found on the Github project.

GMap Examples

To download the latest version of gmap.js you should go to the Github repository.

Download GMap

Published at DZone with permission of Paul Underwood, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)