Reverse Geocoding App - Get Location from Latitude/Longitude

api
locationsensor
beginner
webapi

#1

This tutorial will show you how to retrieve a location given a Latitude and Longitude.
We will use the Location Sensor to get the Latitude and Longitude for this app.
This app will return the country you are currently in.

This app uses the OpenCageData API. You can get an API key for it here.

Design
Design

The Design for this app is extremely simple: A Button and a Label.
You’ll need to add a Web API component and a Location Sensor to this app.

Blocks

The only variable we need for this app is the API key I mentioned above. Set the variable API to this key.

getkey

variable

The API URL is in the form https://api.opencagedata.com/geocode/v1/json?q=LAT+LNG&key=YOUR-API-KEY.

We need to use a join block to get this URL from our Latitude, Longitude and API key.
We have already set the app variable ‘API’ to our API key, now we just need to use the Location Sensor to get our current Latitude and Longitude.

The following blocks get the current location, then piece together the API URL.

Before we look at the GetResponse function, let’s look at the OpenCage API. You can access a demo of the API here, which lets you look at a sample JSON response.

Make sure the ‘Reverse Geocoding’ option is selected, then click the ‘Geocode’ button, then click the ‘JSON Response’ tab.

I’ll use this demo’s sample co-ordinates when I get the Web API response so you should be able to follow along and narrow down the information we’re getting from this API.

We want to return the property ‘country’. Looking at this response, ‘country’ is inside ‘components’…

countryparent

…and ‘components’ is in ‘results’.

So we want the property ‘country’ of the property ‘components’ of the property ‘results’ of our response!

Let’s start by getting the ‘response’ of our API:

response

Then the property ‘results’ of this response:

We can see that this response is in square brackets, which means that any future blocks will treat this as a 1-item list rather than a single item.

We can get around this by treating it like a list ourselves, and getting the first item of this ‘list’ - which is the response object.

We can see that the response no longer has square brackets around it:

So now we get the property ‘components’ of ‘results’:

While you can obviously display whatever properties you want from here, we’re going to get the ‘country’ property:

And there we are! Feel free to use some Text blocks to reformat this response however you want.

You can find a copy of this app here.


Google Places API (JSON) and List Viewer
Payment through Payment Gateway API
Need Help Decoding JSON
#2

So cool – thanks for putting this together Jane!


#3

I’m glad you like it! :smile: