All Collections
Developer Guides
UbiFunctions: Integrate Google's Geolocation API with Ubidots
UbiFunctions: Integrate Google's Geolocation API with Ubidots

Learn to integrate the Geolocation API from Google with Ubidots using UbiFunctions

Isabel Lopez avatar
Written by Isabel Lopez
Updated over a week ago

Google offers a large catalog of API's to developers, each one focusing on different problems worth solving. One of these APIs is the Geolocation API which returns an approximate  geolocation,  based on a either  cellular tower IDs,  or WiFi routers. In the IoT era, this API service has gain importance because it erases the need of a GPS chip in your device, which instead “sniffs” the surrounding cell or WiFi signals  to determine its location.

In this tutorial we will demonstrate how to setup a Parser to make a request to the Google’s API, process the tower location data, and post the final position variable back in Ubidots.

So, let's get started:

Requirements

Step-by-Step

  1. Google Maps Platform Setup

  2. UbiFunction Configuration

  3. Verification of Data Flow

  4. Results

1. Google Maps Platform Setup

1. First go to Google Maps Platform, then in the up-right corner click on "SIGN IN" to login to your google account.

2. Click on "GET STARTED" to add products to your google accounts.

3. A pop up will appears, select "Places", this includes the Geolocation API. Then click on "CONTINUE".

4. Next, assign a name to your project, in this case "Ubidots." Then, select "Yes" once you have read and agreed to the terms of service.

5. You will be redirected  to create a billing account for this project, click on "CREATE BILLING ACCOUNT" to continue.

6. Once you’ve entered the appropriate billing information, click "Start my free trial".

After you’ve completed registration with Google’s Map Platform you will be able to obtain an API Key, which will be used to authenticate each API request.

7. With an active Google Maps Platform account you will have access to an API Key. To locate the API Key for you account go to "Credentials" section into your Google APIs Console.

2. UbiFunction Configuration

1. With the API Key on file, go to your Ubidots account, then access to UbiFunction selecting Data –> Functions.

2. Next, create a new Function by clicking the blue "+" in the top-right of your user interface.

3. Name the new Function as you desire and assign the POST method of communication. In this case we called ours "Geolocation". 

Note: As you probably have seen, an endpoint was created, that means the function was created successfully.

4. Then click on "Make it live" to finish creating the function

5. The UbiFunction sample code below will make a request to the Google Geolocation API using cellular towers JSON message collected from a moving device, namely:

  • Cell Tower ID: A unique number to identify a base transceiver station.

  • Location Area Code: A set of base stations grouped to optimize signalling.

  • Mobile Network Code: A 3 digits number to identify the mobile network operator. Usually it is used in combination with the Mobile Country Code.

  • Mobile Country Code: A unique 3 digits number to identify the country the mobile network operator belongs to. Usually used in combination with the Mobile Network Code.

The code immediately below represents what and how your JSON message should be sent to Ubidots to ensure that your UbiFunction will run properly. 

Sample JSON message from hardware

{
  "deviceID": "geoloc",
  "cellTowers": [
    {
      "cellId": 21532831,
      "locationAreaCode": 2862,
      "mobileCountryCode": 214,
      "mobileNetworkCode": 7
    }
  ]
}

With the JSON message from the hardware received, it will be forwarded via the UbiFunction to Google’s API which will post the triangulated latitude, longitude, and accuracy to your Ubidots account as Position, Accuracy, and Tower variables:

  1. Position variable represents the hardware’s Latitude and Longitude values reported to Ubidots as context. 

  2. Accuracy variable represents an estimated location, in meters. This represents the radius of a circle around the defined “Position” variable. 

  3. Tower variable represents the number of cellular towers that the hardware was able identify in its area. 

To manage and handle the UbiFunction copy and paste the sample code below into the UbiFunction IDE window, making sure to update your Ubidots TOKEN and Google API-Key along the way.

var request = require('request-promise');
var ubidotsToken = "YOUR-UBIDOTS-TOKEN-HERE";
var googleAPIKey = "YOUR-GOOGLE-API-KEY-HERE";
async function requestGoogle(token, data) {
   var options = {
       method: 'POST',
       url: 'https://www.googleapis.com/geolocation/v1/geolocate?key=' + token,
       body: data,
       json: true,
       headers: {
           'Content-Type': 'application/json',
       }
   };
   return await request.post(options);
}
async function ubidotsPostRequest(device_label, data) {
   var options = {
       method: 'POST',
       url: 'https://industrial.api.ubidots.com/api/v1.6/devices/' + device_label,
       body: data,
       json: true,
       headers: {
           'Content-Type': 'application/json',
           'X-Auth-Token': ubidotsToken
       }
   };
   return await request.post(options);
}
async function main(params) {
   var response = await requestGoogle(googleAPIKey, params);
   var latitude = response["location"]["lat"];
   var longitude = response["location"]["lng"];
   var accuracy = response["accuracy"];
   var towers = params["cellTowers"].length;
   var deviceID = params["deviceID"];
   var payload = {"towers": towers, "position": {"value": 1, "context": {"lat": latitude, "lng": longitude}}, "accuracy": accuracy};
   var U_post = await ubidotsPostRequest(deviceID, payload);
   console.log(payload)
   return {U_post};
}

3. Verification of Data Flow

1. To test the UbiFunction, click on "Run Function" to send a request to the Google API.

14. The “Run function” button will bring a  modal window where you can enter a dummy input below to test your unction. Here’s a sample input payload that you can use:

{
  "deviceID": "geoloc",
  "cellTowers": [
    {
      "cellId": 21532831,
      "locationAreaCode": 2862,
      "mobileCountryCode": 214,
      "mobileNetworkCode": 7
    }
  ]
}

4. Verification of Data Flow

  1. To test the UbiFunction, click on "Run function" to send a request to the Google API.

2. The “Run function” button will bring a  modal window where you can enter a dummy input below to test your UbiFunction. Here’s a sample input payload that you can use:

{
  "deviceID": "geoloc",
  "cellTowers": [
    {
      "cellId": 21532831,
      "locationAreaCode": 2862,
      "mobileCountryCode": 214,
      "mobileNetworkCode": 7
    }
  ]
}

3. Click "Run with this input" to execute the function code.

4. After a few seconds, the results of the UbiFunction will be displayed.

IMPORTANT NOTE: All successful parsing functions will obtain the status code 201, this means that the variable was created or updated.

4. Results

Go to the Devices section of your Ubidots account and locate the device used in the UbiFunction. As you open the device you will find 3 new variables created "Towers", "Position" and "Accuracy". 

  • The Towers variable will contains the numbers of cell towers of each request;

  • the Position variable will contain the latitude and longitude of the device as context;

  • the Accuracy variable which represents the estimated radius around the position variable, defining the location. 

To add a Map to your Ubidots dashboard and plot the position returned from your Google API UbiFunction, simply add Map widget to your Ubidots Dashboard with the devices you wish to track. 

Additional details to setting up an Ubidots Map Widget can be found easily in Ubidots’ Help Center. 

Other developers also found useful:

Did this answer your question?