Mon. Feb 3rd, 2020

SVMAKERS.ORG

Shenango Valley Makers

Introduction to positionstack’s Forward and Reverse Batch Geocoding REST API

Welcome to today’s tutorial on apilayer’s positionstack, a forward and reverse batch geocoding REST API. For those that don’t know, forward geocoding translates a street address to GPS coordinates and reverse geocoding converts GPS coordinates to a street address. Batch geocoding allows you to convert a large volume of street addresses to GPS coordinates and vice versa.

In addition to regular forward and reverse geocoding needs, positionstack’s batch mode would be a good fit for companies that regularly collect a large number of customer street addresses and wants to convert them to GPS or vice versa, or has a backlog of such data to convert.

positionstack has more than two billion addresses worldwide in its database. And, its service scales to manage more than one billion geocode API lookups per day.

Home page of apilayer’s positionstack, a forward, reverse and batch geocoding REST API.

In addition to geocoding, positionstack offers embeddable maps as URLs which you can place on a web page, mobile application, et al. For example, scroll down the home page to the API Demo:

Request geocoding for any worldwide location using the API Demo form at positionstack.com

Request geocoding for any worldwide location using the API Demo form at positionstack.com

I just typed in “Space Needle” and clicked the GEOCODE button and grabbed the URL value for map_url in the JSON results. Here’s the map image URL it returned, with the Space Needle in the middle:

Example screenshot of an embeddable map using the positionstack, showing the geographic area surrounding the Seattle Space Needle.

Example screenshot of an embeddable map using the positionstack, showing the geographic area surrounding the Seattle Space Needle.

I encourage you to experiment with the API Demo to explore the JSON format geocoding data.

positionstack also provides results in JSON, XML and GeoJSON, which Wikipedia describes as an open standard format for representing simple geographic features and their non-spatial attributes. These may include points, lines (i.e. streets, highways, and boundaries), polygon regions and multipart collections of these. We’ll explore this with the positionstack API results later within.

The positionstack API also provides results in multiple languages, just designate the two or three-letter code for the language you require.

Highlights of the positionstack API service include real-time geocoding, scalability, global coverage and affordable pricing, free for up to 25,000 geocoding requests monthly.

Highlights of the positionstack API service include real-time geocoding, scalability, global coverage and affordable pricing, free for up to 25,000 geocoding requests monthly.

positionstack is fast and easy to get started with thanks to its three-step quickstart guide and detailed documentation and examples.

Since its a REST API, positionstack can be used from any programming language. To help you get started quickly, it includes coding examples for PHP, Python, Node.js, jQuery, Go and Ruby. And, it’s scalable to grow with your requirements up to millions of requests per minute.

There is also a status page where you can review the nearly 100% uptime of the service.

The company behind positionstack is apilayer. This is my eleventh article about its services, and I’ve become a big fan of the simplicity and accessibility of its services. apilayer provides similar pricing models, sign up, quickstart guides and well structured documentation. It is truly a web and application developers’ go-to API collection.

Here are a few of apilayer’s services I’ve written about previously at ProgrammableWeb:

If you’ve used any apilayer service before, getting started with the positionstack API will be familiar to you. The documentation and REST API structure is consistent across its suite of products, most of which are perfect for strengthening your application or website.

If you’re a startup or independent developer, apilayer always offers a generous free plan with all its services, as it has with the positionstack API’s free 25,000 geocoding requests per month.

Let’s begin exploring!

Getting Started with the positionstack API

To begin using positionstack, you’ll need to register for an account, the free account level is great for exploring the API and initial usage. From positionstack.com, click the blue GET FREE API KEY button to register.

Get Your Free positionstack API Key

You’ll land on the introductory pricing matrix. The Free plan includes 25,000 forward and reverse geocoding API requests. A paid plan is required to access HTTPS encryption, extended rate limits, choice of response format e.g. JSON, XML or GeoJSON, embeddable maps and results in multiple languages.

Screenshot of positionstack pricing page. Sign up for free, or choose from four paid plans: Basic, Professional, Business or Enterprise. The free account provides 25,000 requests.

Screenshot of positionstack pricing page. Sign up for free, or choose from four paid plans: Basic, Professional, Business or Enterprise. The free account provides 25,000 requests.

Batch requests require a paid Professional plan or higher. By paying yearly, you can save 20 percent on any paid plan.

The Sign Up Form

Once you’ve chosen a plan you’ll be asked to complete a Sign Up form. It’s very straightforward:

positionstack sign up and registration form. The example shown is the free plan with email, password, name and address information. The image shows the below the scroll portion of the form for Company Details and Google CAPTCHA at the right.

positionstack sign up and registration form. The example shown is the free plan with email, password, name and address information. The image below shows the the scroll portion of the form for Company Details and Google CAPTCHA at the right.

Once you click Sign Up, a welcome letter with links to the documentation will arrive in your email.

The welcome email from positionstack forward geocoding, reverse geocoding and batch geocoding API includes a link to the documentation and their customer support email.

The welcome email from positionstack forward geocoding, reverse geocoding and batch geocoding API includes a link to the documentation and their customer support email.

Let’s check out the Dashboard, which customers of other apilayer services will immediately recognize. If you use one apilayer service, getting started with any of the others is quite simple.

The positionstack API Dashboard

positionstack’s API dashboard provides your API key and a simple 3-step quickstart guide:

Step 1 – Your API Access Key

Your API access key provides access to the positionstack API. It’s required to be included as a parameter in every call. You can also reset the key to secure a new one whenever you wish.

The positionstack API 3-Step Quickstart Guide for getting started with its batch geocoding API with embedded Open Street Maps. Shows Step 1: Your API access key.

The positionstack API 3-Step Quickstart Guide for getting started with its batch geocoding API with embedded Open Street Maps. Shows Step 1: Your API access key.

Step 2 – Make Your First API Request

Here, you can explore both forward and reverse geocoding from a tabbed base dialog:

positionstack API Quickstart Make API Request screenshot. It shows the parameters for a REST API request for forward and reverse geocoding.

positionstack API Quickstart Make API Request screenshot. It shows the parameters for a REST API request for forward and reverse geocoding.

If you’re logged in to your free or paid account, you can just click on the endpoint URL. Or, you can copy and paste the URL with your access key into a browser.

I’ll try accessing the endpoint without optional parameters. You will need to replace the letter x’s below with your API access key.

Forward geocoding takes a street address and converts it to GPS and additional feature data such as embeddable maps.


https://api.positionstack.com/v1/forward?access_key=xxxxx&query=1600%20Pennsylvania%20Ave%20NW,%20Washington%20DC

Your browser will return the results in RAW JSON which I’ve prettied with JSONFormatter which a reader suggested I try recently. I don’t usually pay attention to links in comments but this one addressed a shortcoming with my usual parser. Here is the first data point returned in JSON:

{
  "data": [
    {
      "latitude": 38.897675,
      "longitude": -77.036547,
      "type": "address",
      "name": "1600 Pennsylvania Avenue NW",
      "number": "1600",
      "postal_code": "20500",
      "street": "Pennsylvania Avenue NW",
      "confidence": 1,
      "region": "District of Columbia",
      "region_code": "DC",
      "county": null,
      "locality": "Washington",
      "administrative_area": null,
      "neighbourhood": "White House Grounds",
      "country": "United States",
      "country_code": "USA",
      "continent": "North America",
      "label": "1600 Pennsylvania Avenue NW, Washington, DC, USA",
      "map_url": "https://map.positionstack.com/export/embed.html?bbox=-77.036047,38.898175,-77.037047,38.897175&layer=mapnik&marker=38.897675,-77.036547"
    },

You can try reverse geocoding similarly.

positionstack API example of reverse geocoding, translating a GPS coordinate to a street address.

positionstack API example of reverse geocoding, translating a GPS coordinate to a street address.

Step 3 – Integrate into Your Application

To finish the quickstart and move on, let’s dive into the API more closely.

Screenshot of third step of the positionstack API Quickstart, Integrate into your web, mobile or cloud-based application

Screenshot of the third step of the positionstack API Quickstart, Integrate into your web, mobile or cloud-based application.

positionstack provides coding examples for six languages: PHP, Python, Node.js, jQuery, Go and Ruby. To take a look at how you might use positionstack from code, here’s a Ruby example:

require 'uri'
require 'net/http'
uri = URI('https://api.positionstack.com/v1/forward')
params = {
    'access_key' => 'YOUR_ACCESS_KEY',
    'query' => '1600 Pennsylvania Ave NW',
    'region' => 'Washington',
    'limit' => 1
}
uri.query = URI.encode_www_form(params)
response = Net::HTTP.get_response(uri)
puts response.read_body

I’ll show more of these programming examples further below.

If you commonly use these APIs from JavaScript frontends, it’s a reasonably good idea to change your access key on a regular schedule. To protect your account usage, you can reset your key from the account dashboard, click the black reset button beside your API key.

Exploring positionstack’s real-time geocoding APIs

Now, I’m ready to walk you through each of the positionstack API endpoints. I encourage you to browse along with positionstack’s excellent documentation on your own:

positionstack's documentation for its forward and reverse geocoding, batch geocoding, embedded images and more.

positionstack’s documentation for its forward and reverse geocoding, batch geocoding, embedded images and more.

Let’s get started.

Forward Geocoding

Forward geocoding takes a street address and converts it to GPS and additional feature data such as embeddable maps. For example, let’s get the GPS coordinate for Seattle’s Theo Chocolate Factory, this really is one of the yummiest places to meet your Fair Trade chocolate needs. Its located at the address 3400 Phinney Avenue North, Seattle, WA 98103 but how can I find it via GPS, forward geocoding.

positionstack provides detailed documentation for API parameters you can use, but here we’ll focus on just the top two. I’ll touch on the advanced parameters in other feature sections below.

example of positionstack documentation for API GET request parameters in its geocoding API.

example of positionstack documentation for API GET request parameters in its geocoding API.

Using these, I construct the following API request to query Theo’s street address. You will need to replace the series of x characters with your API access key.

https://api.positionstack.com/v1/forward?access_key=xxxxx&query=3400%20Phinney%20Avenue%20North,%20Seattle,%20WA%2098103

And boom, there it is! The JSON data for the first point relating to the street address:

{
  "data": [
    {
      "latitude": 47.650884,
      "longitude": -122.354099,
      "type": "address",
      "name": "3400 Phinney Ave N",
      "number": "3400",
      "postal_code": "98103",
      "street": "Phinney Ave N",
      "confidence": 1,
      "region": "Washington",
      "region_code": "WA",
      "county": null,
      "locality": null,
      "administrative_area": null,
      "neighbourhood": "Fremont",
      "country": "United States",
      "country_code": "USA",
      "continent": "North America",
      "label": "3400 Phinney Ave N, WA, USA",
      "map_url": "https://map.positionstack.com/export/embed.html?bbox=-122.353599,47.651384,-122.354599,47.650384&layer=mapnik&marker=47.650884,-122.354099"
    },

Theo is located at GPS point 47.650884, -122.354099 or at least within 10 feet of there. You may remember, the non-military GPS was purposefully limited in its exact accuracy to prevent children from stealing all of Theo’s chocolate with their phones.

positionstack provides clear documentation of each of the JSON response data structure above:

JSON response data.

For example, results > neighbourhood is Fremont. Theo’s Chocolate is indeed located in colorful Fremont, a formerly hippie-ish neighborhood in Seattle which still to this day host the city’s only naked bicycle ride. Since Amazon added 50,000 employees to Seattle over the last decade, the hippies mostly left but the famed Fremont Troll under the bridge remains.

For all paid accounts, Basic and above, you can also request XML or GeoJSON format. For example, the following query with preceding parameter output=geojson returns a GeoJSON formatted response:

https://api.positionstack.com/v1/forward?access_key=xxxxx&output=geojson&query=3400%20Phinney%20Avenue%20North,%20Seattle,%20WA%2098103

{
  "data": {
    "type": "FeatureCollection",
    "features": [
      {
        "type": "Feature",
        "geometry": {
          "type": "Point",
          "coordinates": [
            -122.354099,
            47.650884
          ]
        },
        "properties": {
          "type": "address",
          "name": "3400 Phinney Ave N",
          "number": "3400",
          "postal_code": "98103",
          "street": "Phinney Ave N",
          "confidence": 1,
          "region": "Washington",
          "region_code": "WA",
          "county": null,
          "locality": null,
          "administrative_area": null,
          "neighbourhood": "Fremont",
          "country": "United States",
          "country_code": "USA",
          "continent": "North America",
          "label": "3400 Phinney Ave N, WA, USA",
          "map_url": "https://map.positionstack.com/export/embed.html?bbox=-122.353599,47.651384,-122.354599,47.650384&layer=mapnik&marker=47.650884,-122.354099"
        }
      },
...

Now let’s reverse the geocoding process.

Reverse Geocoding

Reverse geocoding takes a GPS coordinate and converts it into a street address and additional feature data such as embeddable maps.

https://api.positionstack.com/v1/forward?access_key=xxxxx&query=1600%20Pennsylvania%20Ave%20NW,%20Washington%20DC

Your browser will return the results in RAW JSON which I’ve prettied with JSONFormatter which a reader suggested I try recently. I don’t usually pay attention to links in comments but this one addressed a shortcoming with my usual parser. Here is the first data point returned in JSON:

I’ve constructed the query with GPS coordinates for Theo, 47.650884, -122.354099:

https://api.positionstack.com/v1/reverse?access_key=xxxx&query=47.650884,-122.354099

The API returns the street address 3400 Phinney Ave N. below:

"data": [
    {
      "latitude": 47.650884,
      "longitude": -122.354099,
      "type": "address",
      "distance": 0,
      "name": "3400 Phinney Ave N",
      "number": "3400",
      "postal_code": "98103",
      "street": "Phinney Ave N",
      "confidence": 1,
      "region": "Washington",
      "region_code": "WA",
      "county": null,
      "locality": null,
      "administrative_area": null,
      "neighbourhood": "Fremont",
      "country": "United States",
      "country_code": "USA",
      "continent": "North America",
      "label": "3400 Phinney Ave N, WA, USA",
      "map_url": "https://map.positionstack.com/export/embed.html?bbox=-122.353599,47.651384,-122.354599,47.650384&layer=mapnik&marker=47.650884,-122.354099"
    },

Batch Requests

Batch requests allow you to submit a large group of either forward or reverse geocoding requests. The request format is similar to as before, except the group of data points or addresses need to be submitted as an HTTP POST element. In other words, you’ll submit the request data via POST instead of as a single query argument.

{
   "batch":[
      {
         "query": "Main Street",
         "country": "US",
         "region": "Minnesota"
      },
      {
         "query": "Main Street",
         "country": "US",
         "region": "Illinois"
      },
      {
         "query": "Main Street",
         "country": "US",
         "region": "Missouri"
      }
   ]
}

The HTTP Get Request variables are otherwise the same as forward and reverse geocoding.

Here is example PHP code of a batch geocoding request, note how I json_encode the query array and configure CURLOPT_POSTFIELDS with the adjusted data before making my cURL request:

<?php
  $access_key = xxxxx;
  $query = json_encode([
    'batch' => [
      ['query'=>'Main Street','country'=>'US','region'=>'Minnesota'],
      ['query'=>'Main Street','country'=>'US','region'=>'Illinois'],
      ['query'=>'Main Street','country'=>'US','region'=>'Missouri'],
      ],
    ]);
  $ch = curl_init();
  curl_setopt($ch,CURLOPT_URL, 'https://api.positionstack.com/v1/forward?access_key='.$access_key);
  curl_setopt($ch,CURLOPT_POST, 1);
  curl_setopt($ch,CURLOPT_POSTFIELDS, $query);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
  $result = curl_exec($ch);
  curl_close($ch);
?>

Here are excerpts from the batch mode geocoding API request showing response elements from each of the three regions:

{
  "data": [
    {
      "latitude": 47.735549,
      "longitude": -94.548447,
      "type": "street",
      "name": "Main St; Main Street North",
      "number": null,
      "postal_code": null,
      "street": "Main St; Main Street North",
      "confidence": 1,
      "region": "Minnesota",
      "region_code": "MN",
      "county": null,
      "locality": "Blackduck",
      "administrative_area": "Blackduck",
      "neighbourhood": null,
      "country": "United States",
      "country_code": "USA",
      "continent": "North America",
      "label": "Main St; Main Street North, Blackduck, MN, USA",
      "map_url": "https://map.positionstack.com/export/embed.html?bbox=-94.548456,47.73356,-94.54837,47.737536&layer=mapnik&marker=47.735549,-94.548447"
    },
  ...
    {
      "latitude": 40.192706,
      "longitude": -87.969042,
      "type": "street",
      "name": "Main Street",
      "number": null,
      "postal_code": null,
      "street": "Main Street",
      "confidence": 1,
      "region": "Illinois",
      "region_code": "IL",
      "county": null,
      "locality": "Royal",
      "administrative_area": "Ogden Township",
      "neighbourhood": null,
      "country": "United States",
      "country_code": "USA",
      "continent": "North America",
      "label": "Main Street, Royal, IL, USA",
      "map_url": "https://map.positionstack.com/export/embed.html?bbox=-87.973536,40.19268,-87.964548,40.192732&layer=mapnik&marker=40.192706,-87.969042"
    },
  …
    {
      "latitude": 38.555303,
      "longitude": -93.960571,
      "type": "street",
      "name": "Main Street",
      "number": null,
      "postal_code": null,
      "street": "Main Street",
      "confidence": 1,
      "region": "Missouri",
      "region_code": "MO",
      "county": null,
      "locality": "Blairstown",
      "administrative_area": "Bogard Township",
      "neighbourhood": null,
      "country": "United States",
      "country_code": "USA",
      "continent": "North America",
      "label": "Main Street, Blairstown, MO, USA",
      "map_url": "https://map.positionstack.com/export/embed.html?bbox=-93.960597,38.554796,-93.960544,38.55581&layer=mapnik&marker=38.555303,-93.960571"
    }
  ]
}

The full response included a handful of more data points.

Additional positionstack API Options

Specifying Response Fields

If you are performing batch geocoding with large data sets, the amount of data returned can be burdensome. positionstack allows you to define just the response fields that you need.

Here are some examples:

fields = results // returns only the "results" object

fields = results.map_url // returns only the embeddable map URL inside "results"
fields = results.latitude,results.longitude // returns both coordinates inside "results"

fields = country.flag // returns only the flag icon inside "country"

Reducing the number of fields requested can improve performance and minimize download bandwidth.

I’ll also describe advanced features below which can also be included or excluded from geocoding requests.

Specify Output Format

While positionstack’s free geocoding API always returns data in JSON format, paid plans can request data in XML or the specialized GeoJSON format.

For example, this query will return a GeoJSON formatted response object.

https://api.positionstack.com/v1/forward
    ? access_key = xxxxx
    & query = 1600 Pennsylvania Ave NW, Washington DC
    & output = geojson

Here’s a topmost excerpt of the resulting GeoJSON data, which is just a different way of structuring geodata:

{
  "data": {
    "type": "FeatureCollection",
    "features": [
      {
        "type": "Feature",
        "geometry": {
          "type": "Point",
          "coordinates": [
            -77.036547,
            38.897675
          ]
        },
        "properties": {
          "type": "address",
          "name": "1600 Pennsylvania Avenue NW",
          "number": "1600",
          "postal_code": "20500",
          "street": "Pennsylvania Avenue NW",
          "confidence": 1,
          "region": "District of Columbia",
          "region_code": "DC",
          "county": null,
          "locality": "Washington",
          "administrative_area": null,
          "neighbourhood": "White House Grounds",
          "country": "United States",
          "country_code": "USA",
          "continent": "North America",
          "label": "1600 Pennsylvania Avenue NW, Washington, DC, USA",
          "map_url": "https://map.positionstack.com/export/embed.html?bbox=-77.036047,38.898175,-77.037047,38.897175&layer=mapnik&marker=38.897675,-77.036547"
        }
      },
...

Read more about output format selection.

Specifying Response Language

With every geocoding request, positionstack allows you to specify the language for the results. In your API request, add a two or three-character language code. For example, the query below requests forward geocoding results in French using language=fr.

https://api.positionstack.com/v1/forward?access_key=xxxxx&language=fr&query=1600%20Pennsylvania%20Ave%20NW,%20Washington%20DC

The results are translated as appropriate below:

{
  "data": [
    {
      "latitude": 38.897675,
      "longitude": -77.036547,
      "type": "address",
      "name": "1600 Pennsylvania Avenue NW",
      "number": "1600",
      "postal_code": "20500",
      "street": "Pennsylvania Avenue NW",
      "confidence": 1,
      "region": "District de Columbia",
      "region_code": "DC",
      "county": null,
      "locality": "Washington",
      "administrative_area": null,
      "neighbourhood": "White House Grounds",
      "country": "États-Unis",
      "country_code": "USA",
      "continent": "Amérique du Nord",
      "label": "1600 Pennsylvania Avenue NW, Washington, DC, USA",
      "map_url": "https://map.positionstack.com/export/embed.html?bbox=-77.036047,38.898175,-77.037047,38.897175&layer=mapnik&marker=38.897675,-77.036547"
    },
…

Now, let’s review some of positionstack’s advanced features.

Advanced Features of positionstack’s Geocoding

There are five advanced features incorporated into positionstack’s geocoding API:

  1. Embeddable Maps
  2. Country Module
  3. Sun module
  4. Timezone module
  5. Boundary Box

Embeddable maps require a paid plan of any level. Whereas the other four modules are included in the free plan.

Embeddable Maps

As I demonstrated in the introduction, positionstack provides a map_url in its responses. You can then embed the map_url value in an HTML image tag. For example, if you use the request below:

https://api.positionstack.com/v1/forward?access_key=xxxx&query=1600%20Pennsylvania%20Ave%20NW,%20Washington%20DC

It will return a response object such as:

{
  "data":[
    {"latitude":38.897675,
"longitude":-77.036547,
"type":"address",
"name":"1600 Pennsylvania Avenue NW",
…
"map_url":"https://map.positionstack.com/export/embed.html?bbox=-77.036047,38.898175,-77.037047,38.897175u0026layer=mapniku0026marker=38.897675,-77.036547"
}

Note that the value of the map_url is in a JSON encoded format. You have to decode the entire object to get an HTTP usable image URL. Alternately, here is an example using PHP in which I json_decode a JSON object with only the map_url key and its value:

<?php
$obj = json_decode('{"map_url":"https://map.positionstack.com/export/embed.html?bbox=-73.6473825,40.657276,-73.6470422,40.6573867u0026layer=mapniku0026marker=40.657331,-73.647213"}');
echo $obj->map_url;
?>

This returns the image URL:

https://map.positionstack.com/export/embed.html?bbox=-77.037038,38.897998,-77.038038,38.896998&layer=mapnik&marker=38.897498,-77.037538

You can paste the image URL above into your browser or embed it on a web page as shown below:

<img src="https://map.positionstack.com/export/embed.html?bbox=-77.037038,38.897998,-77.038038,38.896998&layer=mapnik&marker=38.897498,-77.037538" alt="description of the map"/>

Country Module

The Country Module allows you to receive detailed information about the country where your forward or reverse geocoding location exists. You can turn it on by setting parameter country_module=1.

You’ll receive a GPS point near the center of the country, its name, capital, flag and continent as well as global codes, phone dialing, currency, language and more.

Try this query with your access key:

https://api.positionstack.com/v1/forward?access_key=xxxxx&query=1600%20Pennsylvania%20Ave%20NW,%20Washington%20DC&country_module=1

Here’s the response object:

{
  "data": [
    {
      "latitude": 38.897675,
      "longitude": -77.036547,
     ...
      "country": "United States",
      "country_code": "USA",
      "continent": "North America",
      …
     "country_module": {
        "latitude": 39.44325637817383,
        "longitude": -98.95733642578125,
        "common_name": "United States",
        "official_name": "United States of America",
        "capital": "Washington D.C.",
        "flag": "US Flag",
        "area": 9372610,
        "landlocked": false,
        "independent": true,
        "global": {
          "alpha2": "US",
          "alpha3": "USA",
          "numeric_code": "840",
          "region": "Americas",
          "subregion": "Northern America",
          "region_code": "019",
          "subregion_code": "021",
          "world_region": "AMER",
          "continent_name": "North America",
          "continent_code": "NA"
        },
        "dial": {
          "calling_code": "1",
          "national_prefix": "1",
          "international_prefix": "011"
        },
        "currencies": [
          {
            "symbol": "$",
            "code": "USD",
            "name": "US Dollar",
            "numeric": 840,
            "minor_unit": 2
          }
        ],
        "languages": {
          "eng": "English"
        }
      },
     ...

Sun Module

The Sun Module returns astrological data with your forward and reverse geocoding responses. Just set parameter sun_module=1 in your requests.

You’ll receive location-specific sunrise and sunset information in metrics such as regular time, astronomical time, civil time or nautical time and also the sun transit time in this location. The sun transit refers to the moment in time where the sun is highest in the sky in a particular location. It’s the local noon i.e. my friend in Hawaii says the sun is always right overhead at noon, it’s not further above the equator in Seattle.

To experiment with the geocoding sun module, try this API request with your access key:

https://api.positionstack.com/v1/forward?access_key=xxxxx&query=1600%20Pennsylvania%20Ave%20NW,%20Washington%20DC&sun_module=1

Here’s the response you’ll receive:

{
  "data": [
    {
      "latitude": 38.897675,
      "longitude": -77.036547,
      "type": "address",
      "name": "1600 Pennsylvania Avenue NW",
     ...
      "sun_module": {
        "rise": {
          "time": 1579350237,
          "astronomical": 1579344630,
          "civil": 1579348502,
          "nautical": 1579346542
        },
        "set": {
          "time": 1579385577,
          "astronomical": 1579391184,
          "civil": 1579387312,
          "nautical": 1579389272
        },
        "transit": 1579367907
      },

Timezone Module

The Timezone Module allows you to receive detailed information about the country where your forward or reverse geocoding location exists. You can turn it on by setting parameter country_module=1.

You’ll receive a GPS point near the center of the country, its name, capital, flag and continent as well as global codes, phone dialing, currency, language and more.

Try this query with your access key:

https://api.positionstack.com/v1/forward?access_key=xxxxx&timezone_module=1&query=1600%20Pennsylvania%20Ave%20NW,%20Washington%20DC

The response object includes basic timezone information for the location and the offsets from GMT in seconds and hours:

"timezone_module": {
   "name": "America/New_York",
   "offset_sec": -18000,
   "offset_string": "-05:00"
}

Bounding Box Module

The Bounding Box Module can return bounding boxes for many geocoding requests. OpenStreetMaps defines a bounding box as two latitudes and two longitudes that represent a rectangular region. In other words, the latitudes and longitudes represent the left, bottom, right, top ends by defining the minimum longitude, minimum latitude, maximum longitude, and maximum latitude.

Try this query with your access key:

https://api.positionstack.com/v1/forward?access_key=xxxxx&bbox_module=1&query=seattle,washington

While not all data items can provide a bounding box in the result, many do. Here is one from the results:

{
      "latitude": 47.570689,
      "longitude": -122.390698,
      "type": "macrohood",
      "name": "West Seattle",
      …
      "label": "West Seattle, WA, USA",
      "bbox_module": [
        -122.420805753,
        47.4963756158,
        -122.370394685,
        47.5954928409
      ],
      "map_url": "https://map.positionstack.com/export/embed.html?bbox=-122.420805753,47.4963756158,-122.370394685,47.5954928409&layer=mapnik&marker=47.570689,-122.390698"
    },

Here’s the map URL returned, it’s essentially a rectangle region with the West Seattle result in the center:

positionstack geocoding API boundary box example with West Seattle in the center of a rectangular region defined by two latitudes and two longitudes.

positionstack geocoding API boundary box example with West Seattle in the center of a rectangular region defined by two latitudes and two longitudes.

Boundary box image URLs are generated from positionstack.com and these URLs do not need json_decode in my experience.

Additional Features

JSONP Callbacks

positionstack also supports JSONP callbacks. For example, if you specify a function name as a “callback” parameter, the endpoint response will call your function with the results on its return.

For example, the response will be returned so as to call YOUR_FUNCTION() with the response data:

https://api.positionstack.com/v1/forward?access_key=xxxxx&query=1600%20Pennsylvania%20Ave%20NW,%20Washington%20DC&callback=YOUR_FUNCTION

When using JavaScript, in my experience, it was easier just to have the AJAX success method call my functions with the response data. But, what happens when you’re calling the API from a different language?

Here’s an example of using the callback method from PHP, to call a JavaScript function on the page to display the data:

<!-- REQUIRES jquery.js to be included -->
<script src="./jquery.js"></script>
<script>
  function processResult(data) {
    // data is json returned by positionstack
    // replace html in id="results" with string version of data
    $('#results').html(JSON.stringify(data));
    console.log(data);
  }
</script>
<br /><br /><br />
<div id="results">
  The results appear here
  <!--- results displayed as string --->
</div>
<?php
  $query = urlencode('1600 Pennsylvania Ave NW, Washington DC');
  $access_key = 'xxxxxx';
  // Initialize CURL:
  $ch = curl_init('https://api.positionstack.com/v1/forward?access_key='.$access_key.'&query='.$query.'&callback=processResult');
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  // Store the response data from the server in php variable $json
  $json = curl_exec($ch);
  echo '<script type="text/javascript">processResult('.$json.');</script>';
  curl_close($ch);
?>

The positionstack API query is made via PHP cURL. My specified callback is the JavaScript function name processResult(), which must be defined before the API call.

The results will be displayed as a string on the page and sent to the JavaScript console with a structured example.

Let’s look at examples of programming languages you can use to access positionstack’s API.

Programming Language Examples

As I mentioned earlier, positionstack provides programming examples for six of the most popular languages: PHP, Python, Node.js, jQuery, Go and Ruby.

Here’s an example for Python 3:

import http.client, urllib.parse
conn = http.client.HTTPConnection('api.positionstack.com')
params = urllib.parse.urlencode({
    'access_key': 'YOUR_ACCESS_KEY',
    'query': 'Copacabana',
    'region': 'Rio de Janeiro',
    'limit': 1,
    })
conn.request('GET', '/v1/forward?{}'.format(params))
res = conn.getresponse()
data = res.read()
print(data.decode('utf-8'))

And, here’s an example of jQuery:

$.ajax({
    url: 'https://api.positionstack.com/v1/forward',
    data: {
      access_key: 'YOUR_ACCESS_KEY',
      query: '1600 Pennsylvania Ave NW - Washington',
      limit: 1
    }
  }).done(function(data) {
    console.log(JSON.parse(data));
  });

The positionstack programming examples make it so easy to quickly integrate the service into your development platform. Making it easy to get started with an API service is one of apilayer’s specialties.

Let’s talk about usage levels and your account.

Upgrading Your Account

positionstack is a subscription-based service and your chosen plan renews automatically each month. You can upgrade, downgrade or cancel anytime.

You might want to upgrade your account for any one combination of these reasons:

  • You require HTTPS encryption for your geocoding API requests, this requires Basic level or above
  • You require three JSON, XML and GeoJSON formats, Embeddable Maps and/or Multiple Language support, this requires Basic level or above
  • You require the high volume geocoding, you’ll require the Basic plan’s Extended Rate Limit
  • You require more than 100,000 API geocoding API requests per month, the Professional plan is required
  • You require more than 1,000,000 API geocoding API requests per month, the Business plan is required
  • You require very high volume e.g. more than 3,000,000 requests per month or other scalability needs or custom features, contact positionstack for a custom Enterprise level solution and a price quote

To make changes, visit your Subscription Plan page from the Dashboard:

positionstack plan and upgrade or downgrade pricing plans for your forward, reverse and batch geocoding REST API requirements.

positionstack plan and upgrade or downgrade pricing plans for your forward, reverse and batch geocoding REST API requirements.

In the above image, you can see I’m on the Business plan but can downgrade to the other plans. Similarly, if I needed a custom enterprise solution, I can click the Request Quote button.

And, positionstack provides a page to calculate your usage statistics in the current period and historically over time. Just visit your Dashboard and click API Usage (I’ve just recently been using my account so the usage is over a brief timeframe.):

The positionstack Dashboard's API Usage page displays the number of geocoding and other API requests all time as well as a statistical daily log for your internal tracking.

The positionstack Dashboard’s API Usage page displays the number of geocoding and other API requests all time as well as a statistical daily log for your internal tracking.

You can use this log to help you in deciding to upgrade or downgrade subscription levels. For example, Free plans are allowed 25,000 geocoding requests per month whereas Basic plans are allowed 100,000, Professional are allowed 1,000,000 and Business level 3,000,000. If that isn’t enough to meet your requirements, contact positionstack for a custom enterprise plan.

In Conclusion

The positionstack API is an exciting addition to the apilayer resources for programmers everywhere. I hope you’ve enjoyed learning about its forward, reverse and batch geocoding REST API.

The folks behind positionstack at apilayer are skillful technologists that provide powerful services at affordable prices with easy to integrate APIs and scalable performance and capacity.

Check out their suite of products and you’ll likely find more developer APIs and business services that interest you. apilayer also offers two other geocoding APIs to check out, ipstack and ipapi, see also my Programmable Web articles on those products: How to Use the ipstack API for Free Geolocation and Determine Timezone, Language and Currency and Introduction to the ipapi Geolocation API.

apilayer and positionstack appreciate your questions, comments, and feedback. You can also follow them on Twitter @apilayer and the apilayer Facebook page.

About apilayer

positionstack is the latest service from apilayer, an established leader in service APIs. It aims to help developers and businesses automate and outsource complex processes by serving them with dedicated and handy programming interfaces.

Two other products by apilayer include aviationstack, the free real-time aviation data and flight tracker API and serpstack, the free google search results page API (aka SERP API), both of which I also wrote about previously for ProgrammableWeb.

Go to Source
Author: <a href="https://www.programmableweb.com/user/%5Buid%5D">jeffreifman</a>