Flight Paths - JavaScript Geolocation Tracking with Google Maps API

Flight Paths – JavaScript Geolocation Tracking with Google Maps API (4/4)

This is the final part of our four-part series on building realtime maps with geolocation tracking for web and mobile web using the JavaScript Google Maps API and PubNub.

What are Flight Paths?

In this tutorial, we’ll add flightpaths using Polylines, which allow you to dynamically draw an updated path through user-specified points on the map hosted in your web or mobile web browser. To demo the capabilities, we place a single polyline and update its endpoint on the fly based on random positions within a bounding box.

Tutorial Overview

The code for this example is available in CodePen here.

If you haven’t already, you first need to take care of a couple of prerequisites we covered in 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

We’ve got our DIV for the application, and the DIV to hold that map already set up from our previous tutorial. So now lets add flight paths.

OK, now let’s get to the good stuff. We define map, mark, and lineCoords variables to hold our map, marker, and polyline coordinates objects so we can manipulate them on the fly as PubNub events will be coming in. Then, we define the initialize callback that the Google Maps JavaScript API can call when it’s ready to load, and ensure it’s a member of the window object so it’s accessible to the API.

var map;
var mark;
var lineCoords = [];

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});
};

window.initialize = initialize;

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);
};

Initialize PubNub

Now that we’ve defined our callbacks, we have all the necessary machinery so we can move on to initializing the PubNub realtime data streaming functionality. First up, we decide the channel name that we’ll expect new position updates to arrive on. Then, we initialize the PubNub library using the publish and subscribe keys we set up earlier in step 1 of the prerequisites.

Finally, we tell the PubNub library to subscribe to the appropriate channel, and attach the redraw function as a listener to the incoming events. What creates those events, you might ask? Stay tuned!

var pnChannel = "map3-channel";

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

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

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);
</script>

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>
  </body>
</html>

Wrapping Up

And that’s it! We hope you found this tutorial series helpful. PubNub and the Google Maps API work wonderfully well together, Google Maps delivering powerful mapping features and functionality, and PubNub connecting them to devices in realtime.

Please reach out if you find any issues, we want to hear from you!

Language:

Use Cases:

Try PubNub Today