Realtime Google Maps Geolocation Tracking with JavaScript

Geolocation and tracking functionality continues to make leaps and bounds. We’ve transcended beyond the static map to interactive and dynamic mapping technology. With that, we’ve seen how vital realtime geolocation tracking has become to apps in every industry, from the on-demand economy to the Internet of Things.

  • Watch your Uber or Lyft move towards you
  • Observe and highlight high-risk areas to fight disease
  • Monitor a fleet of drones
  • Track animals in a protected national park

Realtime tracking casts quite a wide net, eh?

Google Maps Tracking Tutorial Overview

In this tutorial, we’ll get started with geolocation tracking using the Google Maps JavaScript API and PubNub, enabling you to track a device in realtime on a live-updating map. We’ll receive the location and plot its location changes, and include a flight path, which is a draws a history of the route taken.

By the end of the tutorial, we’ll have something that looks like this:

realtime geolocation with google maps api

Google Maps API

Mapping services can get complex, so it makes a lot of sense to use one that is already well-established, robust and feature complete. We’ll use the Google Maps JavaScript API – it has a ton of functionality, and is very easy to get started (but you probably already knew that). Our example app is based on the Google Maps Uluru example available here.

If you’d prefer a different mapping service, we also recommend Mapbox or EON. Both play beautifully with PubNub.

Obtaining Your PubNub Developer Keys

To get started, you’ll need a PubNub account and your unique publish/subscribe keys. If you don’t have an account, you can sign up here, and your pub/sub keys are available in the Admin Dashboard. The keys look like UUIDs and start with “pub-c-” and “sub-c-” prefixes respectively. Keep those handy – you’ll need to plug them in when initializing the PubNub object in your HTML5 app below.

Getting Started with Google Maps

You’ll need a Google Maps API key as well.

  • Step 2: Create or select a project, and click Continue to enable the API and related services.
  • Step 3: On the Credentials page, get an API key and keep it handy for the steps below.

Overall, it’s a pretty quick process. And free to get started, which is a bonus!

Diving into the Code

You’ll want to grab these 64 lines of HTML & JavaScript and save them to a file called pubnub_google_maps.html.

The first thing you should do after saving the code is to replace three values in the JavaScript:

  • YOUR_PUB_KEY: with the PubNub publish key mentioned above.
  • YOUR_SUB_KEY: with the PubNub subscribe key mentioned above.
  • YOUR_GOOGLE_MAPS_KEY: with the Google Maps API key mentioned above.

If you don’t, the UI will not be able to communicate with anything and probably clutter your console log with entirely too many errors. This code is also available as a Gist on GitHub and on Codepen.

Dependencies

First up, we have the JavaScript code & CSS dependencies of our application.

<!doctype html>
<html>
  <head>
    <title>Google Maps Example</title>
    <script src="https://cdn.pubnub.com/sdk/javascript/pubnub.4.4.1.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" />
  </head>
  <body>
  ...
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=YOUR_GOOGLE_MAPS_KEY&callback=initialize"></script>
  </body>
</html>

For folks who have done a front-end implementation with JavaScript before, this should make sense:

  • PubNub JavaScript client: to connect to our data stream integration channel.
  • Google Maps JavaScript client: initialized at the end of the page to ensure functions are declared and available.

In addition, we bring in the CSS features:

  • Bootstrap: in this app, we use it just for vanilla UI presentation.

Overall, we were pretty pleased that we could build a nifty Maps UI with so few dependencies. And with that… on to the UI!

The User Interface

Here’s what we intend the UI to look like:

The UI is super minimal – the map-canvas is a div is inside a Bootstrap container div. We use inline styles, but you’re free to extract those into your own CSS styles if you like.

  <body>
    <div class="container">
      <h1>PubNub Google Maps Example</h1>
      <div id="map-canvas" style="width:600px;height:400px"></div>
    </div>

On to the JavaScript!

The JavaScript Code

Now we’re ready to dive into the pure JavaScript code. It’s not a ton of code, so this should be pretty straightforward.

The first lines we encounter set up our variables lat and lng as global variables so they’re accessible to the asynchronous broadcast function in the setInterval code later in the app (we start at the Golden Gate Bridge, you may start anywhere!). We use map for the Google Map component, mark for the Map Marker, and lineCoords for the list of coordinates in the flight path.

    <script>
    window.lat = 37.8199;
    window.lng = -122.4783;
    var map;
    var mark;
    var lineCoords = [];

Next up, we define the initialization handler and export it to window.initialize. The initialization consists of creating a new map object, a new map marker, and pushing the initial coordinates onto the flight path.

    var initialize = function() {
      map  = new google.maps.Map(document.getElementById('map-canvas'), {center:{lat:lat,lng:lng},zoom:12});
      mark = new google.maps.Marker({position:{lat:lat, lng:lng}, map:map});
      lineCoords.push(new google.maps.LatLng(window.lat, window.lng));
    };

    window.initialize = initialize;

Since we want the map to be live-updating based on incoming broadcast coordinates, we define an event handler called redraw to handle PubNub message events. The redraw function extracts the new lat and lng values from the incoming message, re-centers the map, updates the marker coordinates, and redraws the flight path including the latest segment.

    var redraw = function(payload) {
      lat = payload.message.lat;
      lng = payload.message.lng;

      map.setCenter({lat:lat, lng:lng, alt:0});
      mark.setPosition({lat:lat, lng:lng, alt:0});

      lineCoords.push(new google.maps.LatLng(lat, lng));

      var lineCoordinatesPath = new google.maps.Polyline({
        path: lineCoords,
        geodesic: true,
        strokeColor: '#2E10FF'
      });
      
      lineCoordinatesPath.setMap(map);
    };

Now that we have the infrastructure for redrawing the map, we need to hook up our realtime communications. We set a variable for the PubNub channel where communications will take place, and initialize the PubNub client with our publish and subscribe keys as mentioned above.

    var pnChannel = "map-channel";

    var pubnub = new PubNub({
      publishKey: 'YOUR_PUB_KEY',
      subscribeKey: 'YOUR_SUB_KEY'
    });

To make the map live-updating, we subscribe() the PubNub client to the channel, and register a message event listener to trigger the redraw() function.

    pubnub.subscribe({channels: [pnChannel]});
    pubnub.addListener({message:redraw});

At this point, we have a functioning map listener! We just need to implement the broadcast functionality.

Depending on where you want your broadcast to happen, all you need to do is initialize a PubNub client and start sending messages to the channel. In our case, each message contains lat and lng coordinates for the map display.

In the case of this simple example, we set up an artificial broadcaster that increments the latitude by 0.001 degrees and 0.01 longitude degrees every 5 seconds. In your application, it could be location information from the HTML5 geolocation object, or any other source you can get your hands on (more on that in a bit!).

    setInterval(function() {
      pubnub.publish({channel:pnChannel, message:{lat:window.lat + 0.001, lng:window.lng + 0.01}});
    }, 5000);
  </script>

And that’s it! We close out the body and html tags as shown above.

Not too shabby for 64 lines of HTML & JavaScript!

HTML5 Geolocation

For folks who want to integrate HTML5 geolocation directly from the browser, here’s a snippet (a working CodePen is available here):

navigator.geolocation.getCurrentPosition(function(position) {
  window.lat = position.coords.latitude;
  window.lng = position.coords.longitude;
});

In a production app, you’ll want to be sure to add checks that navigator.geolocation is available, and that the position variable returned has a coordinates attribute!

That concludes this tutorial on realtime tracking with the Google Maps API. Geolocation is definitely one of our favorite subjects, and we’ve got a number of other tutorials around it. Enjoy!

Try PubNub Today

Connect up to 100 devices for Free