JavaScript Geolocation Tracking with Google Maps API
Published: 2024-05-31 14:22:54

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](https://showcase.pubnub.com/?) 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](https://github.com/PubNubDevelopers/PubNub-Showcase/tree/main/web/geolocation) 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,](https://www.pubnub.com/blog/javascript-mapping-javascript-tracking/?) [Two](https://www.pubnub.com/blog/javascript-google-maps-api-map-markers/?) and [Three](https://www.pubnub.com/blog/javascript-google-maps-api-location-publishing/?), where we [set up our JavaScript environment](https://www.pubnub.com/blog/javascript-mapping-javascript-tracking/?) and covered [map markers](https://www.pubnub.com/blog/javascript-google-maps-api-map-markers/?) and [location tracking](https://www.pubnub.com/blog/javascript-google-maps-api-location-publishing/?).

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](https://developers.google.com/maps/documentation/javascript/overview) upon readiness to load. Ensure to replace \`YOUR\_GOOGLE\_MAPS\_API\_KEY\` with your actual **API key**.

```js
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;
```

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.

```js
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
-----------------

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.

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

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.

```js
setInterval(function() {
  pubnub.publish({channel:pnChannel, message:{lat:window.lat + 0.001, lng:window.lng + 0.01}});
}, 500);
```

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

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

Wrapping Up
-----------

This tutorial series has shown us how [Google Maps API](https://developers.google.com/maps/documentation/javascript/overview) and [PubNub](https://www.pubnub.com/?) 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](https://www.pubnub.com/tour/introduction/?) to understand the essential concepts behind every PubNub-powered app in under 5 minutes. Hear about our users' experience directly from our [GitHub page](https://github.com/PubNubDevelopers) and testimonials available on our website.

Get Setup
---------

Sign up for a [PubNub account](https://admin.pubnub.com/#/login?) for immediate access to PubNub keys for free.

Get Started
-----------

The [PubNub docs](https://www.pubnub.com/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.