Geolocation Tracking with the Google Maps API
Published: 2024-03-24 20:32:36

_This is Part Three of our four-part series on building real-time maps and the geolocation API to track devices using the Google Maps platform and PubNub._

What is Geolocation Tracking?
-----------------------------

In this beginners tutorial, we’ll build an app that live-updates the Google Maps JavaScript API map markers we built in [Part Two](https://pubnub.com/blog/javascript-google-maps-api-map-markers/) with live geolocation capabilities. We’ll use the HTML5 geolocation api to collect the user’s location from their device, and stream and publish location changes (based on the device’s self-reported location) to the map using PubNub Real-time Messaging - [real-time location tracking!](https://www.pubnub.com/solutions/geolocation/)

![pubnub_javascript_location](https://images.ctfassets.net/3prze68gbwl1/asset-17suaysk1qa1k10/8880f7c3626a4c6e3d3c03df0427875e/pubnub_javascript_location-889x1024.png "pubnub_javascript_location")

Tutorial Overview
-----------------

The [code for this example is available in CodePen here.](https://codepen.io/team/PubNub/pen/OOKXyg)

[Note that you will need to specify your own API key from the Google Cloud Platform to enable the demo.](https://codepen.io/team/PubNub/pen/OOKXyg)

If you haven’t already, you first need to take care of a couple of prerequisites we covered in [Part One](https://pubnub.com/blog/javascript-mapping-javascript-tracking/) and [Two](https://pubnub.com/blog/javascript-google-maps-api-map-markers/), where we [set up our JavaScript environment](https://pubnub.com/blog/javascript-mapping-javascript-tracking/) and [got started with map markers](https://pubnub.com/blog/javascript-google-maps-api-map-markers/).

Now that we have all of the relevant configuration settings and we have our map markers, let’s get started with collecting and publishing location data for our web or mobile web map.

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 it’s time to use the HTML5 location API for updating our location in real time.

### HTML5 Location API

Let’s take it one step at a time. First we set up an initial latitude and longitude in the general vicinity of San Francisco. Then, we create a function for getting device location using the HTML5 location API and updating the browser location variables. We set an interval timer for periodically obtaining the device location. For convenience, we create return a JavaScript object containing those values as latitude and longitude.

The following JavaScript code snippet shows how to get the current location of the user:

```js
<script>
window.lat = 37.7850;
window.lng = -122.4383;
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(updatePosition);
    }
    return null;
};
function updatePosition(position) {
  if (position) {
    window.lat = position.coords.latitude;
    window.lng = position.coords.longitude;
  }
}
setInterval(function(){updatePosition(getLocation());}, 10000);
function currentLocation() {
  return {lat:window.lat, lng:window.lng};
};
```

OK, now that we have the HTML5 location stuff out of the way, let’s get to the good stuff.

### Live Location

We define map and mark variables to hold our map and marker 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.

```js
var map;
var mark;
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;
```

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 and marker objects to update the position 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});
};
```

Now that we’ve defined our callbacks, we have all the necessary machinery so we can move on to initializing the PubNub real-time 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](https://pubnub.com/blog/javascript-mapping-javascript-tracking/).

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!

```js
var pnChannel = "map2-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 5000 milliseconds, we invoke the anonymous callback function which publishes a new latitude/longitude object (created by the currentLocation() call) to the specified PubNub channel.

```js
setInterval(function() {
  pubnub.publish({channel:pnChannel, message:currentLocation()});
}, 5000);
</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.

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

Next Steps
----------

We’re 75% of the way finished, and now it’s time to add our final feature in [Part Four, flight paths](https://pubnub.com/blog/javascript-google-maps-api-flight-paths/)! Flight paths will show what route our device has taken by drawing a trail behind the map marker.

#### Contents

[What is Geolocation Tracking?](#h-0)[Tutorial Overview](#h-1)[Code Walkthrough](#h-2)[HTML5 Location API](#h-3)[Live Location](#h-4)[Publishing Lat/Long](#h-5)[Next Steps](#h-6)

How can PubNub help you?
========================

This article was originally published on [PubNub.com](https://www.pubnub.com/blog/geolocation-tracking-with-google-maps-api/)

Our platform helps developers build, deliver, and manage real-time interactivity for web apps, mobile apps, and IoT devices.

The foundation of our platform is the industry's largest and most scalable real-time edge messaging network. With over 15 points-of-presence worldwide supporting 800 million monthly active users, and 99.999% reliability, you'll never have to worry about outages, concurrency limits, or any latency issues caused by traffic spikes.

Experience PubNub
-----------------

Check out [Live Tour](https://www.pubnub.com/tour/introduction/) to understand the essential concepts behind every PubNub-powered app in less than 5 minutes

Get Setup
---------

Sign up for a [PubNub account](https://admin.pubnub.com/signup/) 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 or [SDK](https://www.pubnub.com/docs)