DEV Community

Cover image for JavaScript Geolocation Tracking with Google Maps API
PubNub Developer Relations for PubNub

Posted on

JavaScript Geolocation Tracking with Google Maps API

Here's the updated blog post, with all the keywords seamlessly embedded.

This is a conclusion to the four-segment series about creating live, real-time web applications with geolocation features using the Google Maps JavaScript API and PubNub. Our tutorial will walk you through the user experience of generating flight paths using JavaScript and PubNub.

For a example of how this is all implemented check out our Showcase demo found on the PubNub website. Navigate to the Geolocation demo for how we incorporate PubNub with real-time tracking. For the code behind the demo navigate to our Github to see how it all works.

What are Flight Paths?

Flight paths, as implemented in this tutorial, refer to Polylines which allow the dynamic drawing of paths through user-specified points on a map that resides either on your mobile devices or web browser. They are integral to the HTML5 Geolocation API and Google Maps API for tracking movement patterns.

Tutorial Overview

Ensure you have the completed prerequisites from Parts One, Two and Three, where we set up our JavaScript environment and covered map markers and location tracking.

Once you’ve done so, move onto the next part.

Code Walkthrough

Let's start by defining let\ variables map\, mark\, and lineCoords\ to hold our map, marker, and polyline coords objects. By doing so, we can adjust them as PubNub events come in. Subsequently, we define the initialize\ callback which is usable by the Google Maps JavaScript API upon readiness to load. Ensure to replace YOUR\_GOOGLE\_MAPS\_API\_KEY\ with your actual API key.

let map;
let mark;
let lineCoords = [];
let 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});
};
window.initialize = initialize;
Enter fullscreen mode Exit fullscreen mode

Now, with 'redraw' event handler, we will update the new location info on the fly invoking geolocation's getCurrentPosition()\ method.

Lat/Long

Next up, we define a redraw event handler which we’ll call whenever we get a new position changed event on the fly. In the first part of the function, we set the latitude and longitude to the new values from the message. Then, we invoke the appropriate methods on the map, marker, and polyline objects to update the position, add it to the end of the line and recenter the map.

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);
};
Enter fullscreen mode Exit fullscreen mode

Initialize PubNub

After defining our callbacks, we will initialize the PubNub real-time data streaming functionality which operates on mobile phones, tablets, browsers, and laptops across tech stacks like iOS, Android, JavaScript, .NET, Java, Ruby, Python, PHP, and more.

const pnChannel = "map3-channel";
const pubnub = new PubNub({
  publishKey:   'YOUR_PUB_KEY',
  subscribeKey: 'YOUR_SUB_KEY'
});
pubnub.subscribe({channels: [pnChannel]});
pubnub.addListener({message:redraw});
Enter fullscreen mode Exit fullscreen mode

PubNub's functionality to publish and subscribe to topics in real-time channels gives efficient data-streaming capabilities.

Publishing Lat/Long

For this simple tutorial, we set up a basic JavaScript interval timer to publish new positions based on the current time. Every 500 milliseconds, we invoke the anonymous callback function which publishes a new latitude/longitude object (with Northeast-moving coordinates) to the specified PubNub channel. In your app, you’ll likely be getting the position from a live device position or user-reported location.

setInterval(function() {
  pubnub.publish({channel:pnChannel, message:{lat:window.lat + 0.001, lng:window.lng + 0.01}});
}, 500);
Enter fullscreen mode Exit fullscreen mode

Last but not least, we initialize the Google Maps API at the very end to ensure the DOM elements and JavaScript prerequisites are satisfied.

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=YOUR_GOOGLE_MAPS_API_KEY&callback=initialize"></script>
Enter fullscreen mode Exit fullscreen mode

Wrapping Up

This tutorial series has shown us how Google Maps API and PubNub work exceptionally well together for real-time location tracking on web and mobile apps. It's similar to how ride-hailing services like Uber and Lyft show the movement of their vehicles in real time.

Experience PubNub

Check out the Live Tour to understand the essential concepts behind every PubNub-powered app in under 5 minutes. Hear about our users' experience directly from our GitHub page and testimonials available on our website.

Get Setup

Sign up for a PubNub account for immediate access to PubNub keys for free.

Get Started

The PubNub docs will get you up and running, regardless of your use case. We have sections dedicated to JavaScript Google Maps API and how to use them with real-time tracking in our SDK.

Top comments (0)