Reverse Geo-coding From the Linux Command Line

by scanos in Circuits > Linux

1783 Views, 10 Favorites, 0 Comments

Reverse Geo-coding From the Linux Command Line

putty1.png

Reverse geocoding means you know the lat/lng for a location but not the geo attributes, eg town, area, country etc. I needed to do this for a mysql database on my table with lat/lng information. I needed to do this in a hurry so I decided to do it using Linux shell scripting. I won't go into the mysql sql script here but it's reasonably simple. I chose OpenCage Geocoder to achieve this.

Register and Get Your Reverse Geo-coding API From OpenCage

opencage1.png

I went to https://geocoder.opencagedata.com/ and signed up for an api using the free plan. There was a slight complication in that I was restricted to 60 requests per hour so I had to factor that in. The opening page shows an example for curl. This is a similar format to the wget command which I intended to use.

Set Up Putty and Fire Up Your Geo-coding Request

putty1.png
putty2.png
putty3.png
putty4.png

If you don't have it already then download putty.exe and connect to your Linux server.

The first thing I did was to change to the temporary directory

# cd /tmp

Given that your download file is going to start with with js*, check for previously downloaded js* files and remove them. Obviously, this should only be done in the /tmp directory.

# ls js*

# rm js*

Next, activate the request from OpenCage using the following format:

#wget 'https://api.opencagedata.com/geocode/v1/json?q=54.38+-5.5469&pretty=1&key=YOUR_KEY'

Note the speechmarks to enclose the url

This will download to your directory a file beginning with js. You can display the contents by using the cat command with js,i.e. cat js then hit the tab key and it will reveal the complete file name. This file contains a lot of information. In my case, I simply wanted the place name data so I used the following command:

#grep format json\?q\=54.38+-5.5469\&pretty\=1\&key\=MY_KEY

This returned the following:
"formatted" : "Shore Road, Portaferry, United Kingdom",

How to Use These Commands

opencage1.png

1) You can create a shell script by including the commands from the previous step and using latitude and longitude as input arguments.

  1. # cd /tmp
  2. # rm js*
  3. # wget 'https://api.opencagedata.com/geocode/v1/json?q=LATITUDE+-LONGITUDE&pretty=1&key=YOUR_KEY'
  4. #grep format json\?q\=LATITUDE+-LONGITUDE\&pretty\=1\&key\=MY_KEY

You can execute the MYSQL interpreter from the command line to input or output from your script.

2) Embed your shell script within say a PHP file and control the input and output to MySQL from PHP and pass as arguments within the php exec command.

Hope you found this useful.