Real-time Geolocation API JavaScript with Modern Maps
Published: 2024-01-25 21:40:44

Before we begin this tutorial, [sign up for a PubNub account to get your API keys](https://www.pubnub.com/docs/general/basics/set-up-your-account). We offer a generous sandbox tier that won't cost you a dime until it's time to scale!

[Geolocation](https://www.pubnub.com/solutions/geolocation/) and tracking functionality are making continuous advancements. We have moved beyond static maps to a realm of interactive and dynamic API mapping technology. This shift has underscored the indispensable role that a geolocation API assumes in every industry, from the on-demand economy to the [Internet of Things](https://www.pubnub.com/solutions/iot-device-control/).

Real-time tracking certainly casts a wide net, doesn't it?

Google Maps Tracking Tutorial Overview
--------------------------------------

This is a four-part tutorial on building real-time maps for web and mobile web using the Google Maps JavaScript API and PubNub. We'll start with the basics to get your app [set up](https://www.pubnub.com/docs/general/basics/set-up-your-account), then add real-time geolocation functionality in the subsequent parts.

By the end, you'll have a basic JavaScript location tracking app with map markers, device location tracking, and flight paths, powered by the JavaScript Google Maps API and [PubNub](https://www.pubnub.com/docs).

![](/cdn/3prze68gbwl1/5KybCqYQ9RHWnqwpscWRi1/924f8e5e7646c6d70db67b83409c1546/pubnub_javascript_overview-min.png)

Real-Time Location API Setup
----------------------------

### Tutorial Assets

For this tutorial, we presume you are working with a recent evergreen browser on a desktop or mobile device.

### PubNub Setup

To get started, you'll first need your PubNub publish and subscribe keys. If you don’t have an account, you can [sign up here](https://www.pubnub.com/docs/general/basics/set-up-your-account), and your pub/sub keys are available in the [Admin Dashboard](https://dashboard.pubnub.com/login). The keys resemble UUIDs and start with “pub-c-” and “sub-c-” prefixes respectively.

Once you have your pub/sub keys, create a new PubNub application to represent your Android application (and any other systems that communicate using the same channels). The PubNub application will include publish and subscribe keys that applications can use for those specified features.

### Google Maps API Setup

To integrate with Google Maps, you’ll need to create a Google Maps API key. We recommend doing that using the [getting started guide](https://developers.google.com/maps/documentation/javascript/adding-a-google-map#key) here. This creates a unique API key that can be locked down to whatever web apps you like. Once you’ve started to create a bunch of projects, you can manage your credentials in the Google API console here.

Don't forget to enable the 'Maps JavaScript API' in the Google Cloud console after creating your API key.

Real-Time Location API Overview
-------------------------------

In this HTML5 and JavaScript sample application, [PubNub](https://www.pubnub.com/docs) provides the real-time communication capability that allows our web application to receive incoming events as the position of a remote object (latitude and longitude) changes.

The core PubNub functionality that we use is [Real-time Messaging](https://pubnub.com/products/pubnub-platform/). Our application uses a PubNub channel to send and receive position changed events. In this example, the same application both sends and receives the position events, so we say it is both the publisher and subscriber. In your application, the publisher (sender) system(s) may be different from the subscriber (receiving) system(s).

Google Maps Overview
--------------------

We’ll use the [JavaScript Google Maps API](https://developers.google.com/maps/documentation/javascript/overview) and the [HTML5 Map Widget](https://developers.google.com/maps/documentation/embed/get-started) for this tutorial. The HTML5 map widget displays a map of the vicinity you configure. The map size, map center latitude and longitude, zoom level, map style and other options may be configured to your initial preferences and updated on the fly.

The Google Maps JavaScript API provides an initialization callback option that calls a function you specify when the map is loading. In addition, we’ll use features like Map Markers and Polylines which allow you to place friendly [map markers](https://pubnub.com/blog/javascript-google-maps-api-map-markers/) and [flight paths](https://pubnub.com/blog/javascript-google-maps-api-flight-paths/) on the map at the location(s) you specify (Parts 2, 3 and 4). All the points are user-specified and may be updated in real time as updates arrive.

Code Walkthrough
----------------

To work with the code, you’ll want to fork it into your own project using CodePen, or download the HTML code into a file and run it using your favorite HTTP server. We recommend editing code in the CodePen web IDE like this:

![](/cdn/3prze68gbwl1/asset-17suaysk1qa1k0b/9ba4853976e96918d7529ff7b0f9edda/pubnub_javascript_devenv-1024x909.png)

Once you’re in the IDE, you’ll be able to perform the minor code changes to get the app running quickly.

### Application Setup and Configuration

The web page structure should be familiar if you’ve worked with web applications in the past. We start with a plain HTML5 + JavaScript application that has a DIV tag for the map display. We include the PubNub library for real-time communications in the HEAD of the HTML page.

You’ll also want to include the Google Maps API using a SCRIPT tag at the bottom of the HTML page. Check the official Google Maps documentation for the latest version.

Note that you’ll need to replace the placeholder maps API key and version in the SCRIPT SRC attribute accordingly above.

It’s worth mentioning that for HTML5 location to work, you’ll be relying on the user to explicitly allow location access to your app on their device. Handling graceful fallback for cases where location permission is denied is beyond the scope of this tutorial. However, it's essential to make sure you handle these cases in your final application to provide the best user experience.

The PubNub settings are included within a simple JavaScript map. You can update them with your own values as follows:

```js
pubnub = new PubNub({
    publishKey : "myPublishKey",
    subscribeKey : "mySubscribeKey",
    userId: "myUniqueUserId"
});
```

### Running the Code

You don’t need to do anything special to run the app in CodePen – it runs automatically from the online editor. Depending on where you are viewing the app (geolocation), and the capabilities of your connection (WiFi or LTE), you may see different locations reported (IP to geo versus GPS location). We’ve found that different devices, as well as different browsers, have their own location accuracy characteristics, some more accurate than others.

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

With that, we now have our app set up. In [Part Two, we’ll implement live map markers](https://pubnub.com/blog/javascript-google-maps-api-map-markers/), which identify where a device is located on a map.

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

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

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)