Quickstart Guide

Need to get up and running quickly? Click the button below to try our 3-Step Quickstart Guide and start geocoding in under 30 seconds.

Code Examples

You can geocode using any programming language of your choice. Browse code examples for PHP, Python, Node, jQuery, Go and Ruby.

Code Examples

API Documentation

The positionstack API was built to offer a straightforward and reliable solution for forward and reverse geocoding, covering more than 2 billion places and addresses worldwide. Features include batch geocoding, multi-language support, embeddable map URLs, and more. API results can be delivered in JSON, XML or geocode-specific GeoJSON. Average API response times range between 10ms and 100ms depending on the size of your request.

The following API documentation will provide detailed information about API integration methods, available endpoints, request parameters and response objects. In the last section you will be able to browse a series of simple code examples in different programming languages.

Getting Started

API Access Key & Authentication

Each registered positionstack account is associated with a unique API access key, which is used to authenticate with the API when geocoding. You can find your personal API access key by logging in to your account dashboard.

To start making API requests, please authenticate with the API in accordance with the example request below.

https://api.positionstack.com/v1/forward
    ? access_key = YOUR_ACCESS_KEY

Important: Please make sure to keep your API access key safe at all times. If you believe that your API access key is being used by an unauthorized party, you can always generate a new key using your account dashboard.

256-bit HTTPS Encryption Available on: Basic Plan and higher

If you are subscribed to the Basic Plan (or higher) you may access the positionstack API using industry-standard HTTPS. To do so, simply use https in your API request URL as shown in the example below.

Example API Request:

https://api.positionstack.com

JSONP Callbacks

The positionstack API supports JSONP Callbacks. To use JSONP in your API request, simply append callback as a GET parameter to your API request URL and set it to any function name. If a function name is provided, the API will return your API result wrapped in the tags of the function you specified.

Example API Request:

https://api.positionstack.com/v1/forward ? access_key = YOUR_ACCESS_KEY & callback = FUNCTION_NAME

Example API Response:

FUNCTION_NAME ({
   {
   [...]
   }
})              

Please note: The API also supports Access-Control (CORS) headers.

API Errors

If your API request fails, the API will return an error object, which contains the sub-objects code and message indicating which type of error has occurred. If a validation_error occurs, there will be an additional context sub-object containing information about one or multiple validation errors.

The API also supports universal HTTP status codes. For successful API requests, you can expect the HTTP code 200. For the example error below, the HTTP code 422 (Unprocessable Entity) would be returned.

Example Error:

{
   "error": {
      "code": "validation_error",
      "message": "Request failed with validation error.",
      "context": {
         "query": [
            {
               "type": "query_must_be_string",
               "message": "The query must be a string."
            }
         ]
      }
   }
}        

Common API Errors:

Code Type Description
401 invalid_access_key An invalid API access key was supplied.
401 missing_access_key No API access key was supplied.
401 inactive_user The given user account is inactive.
403 function_access_restricted The given API endpoint is not supported on the current subscription plan.
404 invalid_api_function The given API endpoint does not exist.
404 404_not_found Resource not found.
429 usage_limit_reached The given user account has reached its monthly allowed request volume.
429 rate_limit_reached The given user account has reached the rate limit.
500 internal_error An internal error occurred.

Important: API errors are always returned in JSON format, regardless of which output format you may have chosen using the API's output parameter.

API Endpoints

Forward Geocoding Available on: All plans

Forward geocoding is the process of converting a free-text address or place to location data. To make a forward geocoding request, use the API's forward endpoint and specify your query using the query parameter. Other optional parameters are available.

Example API Request:

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

HTTP GET Request Parameters:

Object Description
access_key [Required] Your API access key, which can be found in your acccount dashboard.
query [Required] Specify your query as a free-text address, place name or using any other common text-based location identifier (e.g. postal code, city name, region name).
country [Optional] Filter geocoding results by one or multiple comma-separated 2-letter (e.g. AU) or 3-letter country codes (e.g. AUS). Example: country=AU,CA to filter by Australia and Canada.
Download: Supported Countries (CSV)
region [Optional] Filter geocoding results by specifying a region. This could be a neighbourhood, district, city, county, state or administrative area. Example: region=Berlin to filter by locations in Berlin.
language [Optional] Translate specific API response objects by specifying the 2-letter (e.g. en) or the 3-letter code (e.g. eng) of your preferred language. (Default: English)
country_module [Optional] Set to 1 in order to enable the Country Module to include more extensive country data in your API response. Read more about this in the Country Module section.
sun_module [Optional] Set to 1 in order to enable the Sun Module to include astrology data in your API response. Read more about this in the Sun Module section.
timezone_module [Optional] Set to 1 in order to enable the Timezone Module to include timezone data in your API response. Read more about this in the Timezone Module section.
bbox_module [Optional] Set to 1 in order to enable the Bounding Box Module to include boundary coordinates in your API response. Read more about this in the Bounding Box Module section.
limit [Optional] Specify a limit between 1 and 80 to limit the number of results returned per geocoding query. Batch requests can contain multiple geocoding queries. (Default: 10 results)
fields [Optional] Specify one or multiple response field(s) to decrease API response size. Learn how to use this option in the Specify Response Fields section.
output [Optional] Specify your preferred API output format. Available values: json (default), xml and geojson.
callback [Optional] Use this parameter to specify a JSONP callback function name to wrap your API response in. Learn more about JSONP Callbacks.

Example API Response:

{
   "data": {
      "results": [
         {
            "latitude": 38.897675,
            "longitude": -77.036547,
            "label": "1600 Pennsylvania Avenue NW, Washington, DC, USA",
            "name": "1600 Pennsylvania Avenue NW",
            "type": "address",
            "number": "1600",
            "street": "Pennsylvania Avenue NW",
            "postal_code": "20500",
            "confidence": 1,
            "region": "District of Columbia",
            "region_code": "DC",
            "administrative_area": null,
            "neighbourhood": "White House Grounds",
            "country": "United States",
            "country_code": "US",
            "map_url": "http://map.positionstack.com/38.897675,-77.036547"
         }
      ]
   }
}

Please note: For readability purposes we have reduced the above example API response to show only one geocoding result. To achieve the same result size, you can set the limit parameter to 1.

API Response Objects:

Response Object Description
data Returns two large arrays of data: request and results, explained in more detail below.
results Returns an array of location results for this API request. The number of sub-arrays directly depends on the value specified limit value. All sub-arrays and sub-objects are listed below.
results > latitude Returns the latitude coordinate associated with the location result.
results > longitude Returns the longitude coordinate associated with the location result.
results > label Returns the formatted place name or address.
results > name Returns the name of the location result. This could be a place name, address, postal code, and more.
results > type Returns the type of location result. View all location types
results > number Returns the street or house number associated with the location result.
results > street Returns the street name associated with the location result.
results > postal_code Returns the postal or ZIP code associated with the location result.
results > confidence Returns a confidence score between 0 (0% confidence) and 1 (100% confidence) associated with the location result.
results > region Returns the name of the region associated with the location result.
results > region_code Returns the region code associated with the location result.
results > administrative_area Returns the name of the administrative area associated with the location result.
results > neighbourhood Returns the name of the neighbourhood associated with the location result.
results > country Returns the common name of the country associated with the location result.
results > country_code Returns the ISO 3166 Alpha 2 (two letters) code of the country associated with the location result.
results > map_url Returns an embeddable map associated with the location result.

Reverse Geocoding Available on: All plans

Reverse geocoding is the process of converting coordinates (latitude & longitude) or an IP address to location data. To make a reverse geocoding request, use the API's reverse endpoint and specify your query using the query parameter. Other optional parameters are available.

Example API Request:

https://api.positionstack.com/v1/reverse
    ? access_key = YOUR_ACCESS_KEY
    & query = 40.7638435,-73.9729691

HTTP GET Request Parameters:

Object Description
access_key [Required] Your API access key, which can be found in your acccount dashboard.
query [Required] Specify your query as coordinates in the format latitude,longitude (e.g. query=40.7638435,-73.9729691) or use an IP address for automated coordinate-detection (e.g. query=72.229.28.185).
country [Optional] Filter geocoding results by one or multiple comma-separated 2-letter (e.g. AU) or 3-letter country codes (e.g. AUS). Example: country=AU,CA to filter by Australia and Canada.
Download: Supported Countries (CSV)
region [Optional] Filter geocoding results by specifying a region. This could be a neighbourhood, district, city, county, state or administrative area. Example: region=Berlin to filter by locations in Berlin.
language [Optional] Translate specific API response objects by specifying the 2-letter (e.g. en) or the 3-letter code (e.g. eng) of your preferred language. (Default: English)
country_module [Optional] Set to 1 in order to enable the Country Module to include more extensive country data in your API response. Read more about this in the Country Module section.
sun_module [Optional] Set to 1 in order to enable the Sun Module to include astrology data in your API response. Read more about this in the Sun Module section.
timezone_module [Optional] Set to 1 in order to enable the Timezone Module to include timezone data in your API response. Read more about this in the Timezone Module section.
bbox_module [Optional] Set to 1 in order to enable the Bounding Box Module to include boundary coordinates in your API response. Read more about this in the Bounding Box Module section.
limit [Optional] Specify a limit between 1 and 80 to limit the number of results returned per geocoding query. Batch requests can contain multiple geocoding queries. (Default: 10 results)
fields [Optional] Specify one or multiple response field(s) to decrease API response size. Learn how to use this option in the Specify Response Fields section.
output [Optional] Specify your preferred API output format. Available values: json (default), xml and geojson.
callback [Optional] Use this parameter to specify a JSONP callback function name to wrap your API response in. Learn more about JSONP Callbacks.

Example API Response:

{
   "data": {
      "results": [
         {
            "latitude": 40.763841,
            "longitude": -73.972972,
            "label": "Apple Store, Manhattan, New York, NY, USA",   
            "name": "Apple Store",
            "type": "venue",
            "distance": 0,
            "number": "767",
            "street": "5th Avenue",
            "postal_code": "10153",
            "confidence": 1,
            "region": "New York",
            "region_code": "NY",
            "administrative_area": null,
            "neighbourhood": "Midtown East",
            "country": "United States",
            "country_code": "US",
            "map_url": "http://map.positionstack.com/40.763841,-73.972972",
         }
      ]
   }
}

Please note: For readability purposes we have reduced the above example API response to show only one geocoding result. To achieve the same result size, you can set the limit parameter to 1.

API Response Objects:

Response Object Description
data Returns two large arrays of data: request and results, explained in more detail below.
results Returns an array of location results for this API request. The number of sub-arrays directly depends on the value specified limit value. All sub-arrays and sub-objects are listed below.
results > latitude Returns the latitude coordinate associated with the location result.
results > longitude Returns the longitude coordinate associated with the location result.
results > label Returns the formatted place name or address.
results > name Returns the name of the location result. This could be a place name, address, postal code, and more.
results > type Returns the type of location result. View all location types
results > distance Returns the distance (in meters) between the location result and the coordinates specified in the query parameter. Only applicable for reverse geocoding.
results > number Returns the street or house number associated with the location result.
results > street Returns the street name associated with the location result.
results > postal_code Returns the postal or ZIP code associated with the location result.
results > confidence Returns a confidence score between 0 (0% confidence) and 1 (100% confidence) associated with the location result.
results > region Returns the name of the region associated with the location result.
results > region_code Returns the region code associated with the location result.
results > administrative_area Returns the name of the administrative area associated with the location result.
results > neighbourhood Returns the name of the neighbourhood associated with the location result.
results > country Returns the common name of the country associated with the location result.
results > country_code Returns the ISO 3166 Alpha 2 (two letters) code of the country associated with the location result.
results > map_url Returns an embeddable map associated with the location result.

Batch Requests Available on: Professional Plan and higher

Batch requests are a way of sending multiple forward or reverse geocoding queries to the API at once. While batch requests look very similar to regular geocoding requests, they come with the requirement of an additional HTTP POST request body.

To make a batch request, simply specify your API request URL along with an additional batch request parameter sent as an HTTP POST JSON body carrying multiple queries. You can find an example request containing 3 queries below.

Example Request URL:

https://api.positionstack.com/v1/forward
    ? access_key = YOUR_ACCESS_KEY

Example Request POST Body:

The request body below sends 3 forward geocoding queries to the API at once, looking for a street named "Main Street" across the US regions Minnesota, Illinois and Missouri. While the query parameter is required, the other two are optional and override potential HTTP GET counterparts specified in your API request URL.

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

HTTP GET Request Parameters:

To see all supported HTTP GET request parameters, please refer to the Forward Geocoding or Reverse Geocoding sections.


HTTP POST Request Parameters:

Object Description
query [Required] Specify an address or place name for forward geocoding, or coordinates (e.g. query=40.7638435,-73.9729691) or an IP address for reverse geocoding.
country [Optional] Filter geocoding results by one or multiple comma-separated 2-letter (e.g. AU) or 3-letter country codes (e.g. AUS). Example: country=AU,CA to filter by Australia and Canada.
region [Optional] Filter geocoding results by specifying a region. This could be a neighbourhood, district, city, county, state or administrative area. Example: region=Berlin to filter by locations in Berlin.

Example API Response:

As you can see in the example API response below, batch requests will return one instance of the API's data array for each geocoding query sent in your POST request body. In our example, the API response with 3 instances.

{
    "data": [
        {
            "results": [
                {
                    "latitude": 47.735549,
                    "longitude": -94.548447,
                    "label": "Main St; Main Street North, Blackduck, MN, USA",
                    "name": "Main St; Main Street North",
                    "type": "street",
                    "number": null,
                    "street": "Main St; Main Street North",
                    "postal_code": null,
                    "confidence": 1,
                    "region": "Minnesota",
                    "region_code": "MN",
                    "administrative_area": "Blackduck",
                    "neighbourhood": null,
                    "country": "United States",
                    "country_code": "US",
                    "map_url": "http://map.positionstack.com/47.735549,-94.548447",
                }
            ]
        },
        {
            "results": [
                {
                    "latitude": 42.033423,
                    "longitude": -87.679961,
                    "label": "Evanston Main Street, Evanston, IL, USA",
                    "name": "Evanston Main Street",
                    "type": "venue",
                    "number": "600",
                    "street": "Main Street",
                    "postal_code": "60202",
                    "confidence": 0.8,
                    "region": "Illinois",
                    "region_code": "IL",
                    "administrative_area": "Evanston Township",
                    "neighbourhood": null,
                    "country": "United States",
                    "country_code": "US",
                    "map_url": "http://map.positionstack.com/42.033423,-87.679961",
                }
            ]
        },
        {
            "results": [
                {
                    "latitude": 39.055473,
                    "longitude": -94.58597,
                    "label": "Main Street, Kansas City, MO, USA",
                    "name": "Main Street",
                    "type": "venue",
                    "number": "3933",
                    "street": "Main Street",
                    "postal_code": null,
                    "confidence": 0.8,
                    "region": "Missouri",
                    "region_code": "MO",
                    "administrative_area": "Kaw Township",
                    "neighbourhood": "Hanover Place",
                    "country": "United States",
                    "country_code": "US",
                    "map_url": "http://map.positionstack.com/39.055473,-94.58597"
                }
            ]
        }
    ]
}

Please note: For readability purposes we have reduced the above example API response to show only one geocoding result. To achieve the same result size, you can set the limit parameter to 1.

API Response Objects:

For details about API response objects, please refer to the Forward Geocoding or Reverse Geocoding sections.

Advanced Data

Embeddable Maps Available on: Basic Plan and higher

Each API response will carry a map_url object containing a URL leading to an embeddable map associated with your geocoding result. This map can be embedded using an iFrame element on your website or in your application.

Example map_url Object:

"map_url": "http://map.positionstack.com/47.735549,-94.548447"

Please note: This feature is only available on the Basic Plan and higher.

Country Module Available on: All plans

As part of the Country Module, the positionstack API is capable of returning an extensive set of country information along with both forward and reverse geocoding requests. To enable the Country Module, simply append the API's country_module HTTP GET parameter to your API request URL and set it to 1.

Example API Request:

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

Example country_module Object:

"country_module": {
   "latitude": 39.44325637817383,
   "longitude": -98.95733642578125,
   "common_name": "United States",
   "official_name": "United States of America",
   "capital": "Washington D.C.",
   "flag": "🇺🇸",
   "area": 9372610,
   "landlocked": false,
   "independent": true,
   "global": {
      "alpha2": "US",
      "alpha3": "USA",
      "numeric_code": "840",
      "region": "Americas",
      "subregion": "Northern America",
      "world_region": "AMER",
      "region_code": "019",
      "subregion_code": "021",
      "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": [
      {
         "code": "en",
         "name": "English",
      }
   ]
},

Please note: For readability purposes we have reduced the above example API response to show only one geocoding result and skipped any objects before and after the country_module object shown above.

country_module Sub-Objects Explained:

Response Object Description
latitude Returns the country's latitude coordinate.
longitude Returns the country's longitude coordinate.
common_name Returns the common name of the country associated with the location result.
official_name Returns the official name of the country associated with the location result.
capital Returns the capital of the country associated with the location result.
flag Returns a flag icon of the country associated with the location result.
landlocked Returns true or false depending on whether or not the country is landlocked.
independent Returns true or false depending on whether or not the country is independent.
global > alpha2 Returns the ISO 3166 Alpha 2 code of the country associated with the location result.
global > alpha3 Returns the ISO 3166 Alpha 3 code of the country associated with the location result.
global > numeric_code Returns the numeric ISO 3166 code of the country associated with the location result.
global > region Returns the country's region name. Example: Americas
global > subregion Returns the country's sub-region name. Example: Northern America
global > world_region Returns the country's world region name. Example: AMER
global > region_code Returns the country's region name. Example: Americas
global > subregion_code Returns the country's sub-region code. Example: 021
global > continent_name Returns the continent name of the country associated with the location result.
global > continent_code Returns the continent code of the country associated with the location result.
dial > calling_code Returns the calling code of the country associated with the location result.
dial > national_prefix Returns the national calling prefix of the country associated with the location result.
dial > international_prefix Returns the international calling prefix of the country associated with the location result.
currencies Returns an array of one or multiple currencies associated with the location result.
currencies > symbol Returns the currency symbol of the country associated with the location result.
currencies > code Returns the currency code of the country associated with the location result.
currencies > name Returns the currency name of the country associated with the location result.
currencies > numeric Returns the numeric currency code of the country associated with the location result.
currencies > minor_unit Returns the minor currency unit of the country associated with the location result.
languages Returns an array of one or multiple languages of the country associated with the location result.
languages > code Returns the 2-letter language code of the given language.
languages > name Returns the official name of the given language.

Sun Module Available on: All plans

The API is capable of returning astrology data along with forward and reverse geocoding requests. To enable the Sun Module, simply append the API's sun_module HTTP GET parameter to your API request URL and set it to 1.

Example API Request:

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

Example sun_module Object:

"sun_module": {
   "rise": {
      "time": 1575374970,
      "astronomical": 1575369289,
      "civil": 1575373205,
      "nautical": 1575371219
   },
   "set": {
      "time": 1575409578,
      "astronomical": 1575415260,
      "civil": 1575411343,
      "nautical": 1575413329
   },
   "transit": 1575392274
},

Please note: For readability purposes we have reduced the above example API response to show only one geocoding result and skipped any objects before and after the sun_module object shown above.

sun_module Sub-Objects Explained:

Response Object Description
rise > time Returns the sunrise time as a UNIX timestamp (UTC).
rise > astronomical Returns the astronomical sunrise time as a UNIX timestamp (UTC).
rise > civil Returns the civil sunrise time as a UNIX timestamp (UTC).
rise > nautical Returns the nautical sunrise time as a UNIX timestamp (UTC).
set > time Returns the sunset time as a UNIX timestamp (UTC).
set > astronomical Returns the astronomical sunset time as a UNIX timestamp (UTC).
set > civil Returns the civil sunset time as a UNIX timestamp (UTC).
set > nautical Returns the nautical sunset time as a UNIX timestamp (UTC).
transit Returns the sun transit time as a UNIX timestamp (UTC).

Timezone Module Available on: All plans

The API is capable of returning timezone information along with forward and reverse geocoding requests. To enable the Timezone Module, simply append the API's timezone_module HTTP GET parameter to your API request URL and set it to 1.

Example API Request:

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

Example timezone_module Object:

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

Please note: For readability purposes we have reduced the above example API response to show only one geocoding result and skipped any objects before and after the timezone_module object shown above.

timezone_module Sub-Objects Explained:

Response Object Description
name Returns the common name of the timezone.
offset_sec Returns GMT offset of the timezone in seconds.
name Returns GMT offset of the timezone as a string.

Bounding Box Module Available on: All plans

For many geocoding requests the API is capable of returning accurate bounding box coordinates. To enable the Bounding Box Module, simply append the API's bbox_module HTTP GET parameter to your API request URL and set it to 1.

Not sure about what a bounding box is? Read OpenStreetMap's Bounding Box Definition.

Example API Request:

https://api.positionstack.com/v1/forward
    ? access_key = YOUR_ACCESS_KEY
    & query = Manhattan, New York
    & bbox_module = 1

Example bbox_module Object:

"bbox_module": {
   "min_longitude": -74.047729627,
   "min_latitude": 40.6829169454,
   "max_longitude": -73.9066509954,
   "max_latitude": 40.8790380468
}

Please note: For readability purposes we have reduced the above example API response to show only one geocoding result and skipped any objects before and after the bbox_module object shown above.

bbox_module Sub-Objects Explained:

Response Object Description
min_longitude Returns the minimum longitude coordinate point associated with the location result.
min_latitude Returns the minimum latitude coordinate point associated with the location result.
max_longitude Returns the maximum longitude coordinate point associated with the location result.
max_latitude Returns the maximum latitude coordinate point associated with the location result.

Important: Please note that not all geocoding requests will yield bounding box information.

Options

Specify Response Fields Available on: All plans

Depending on whether or not batch requests are made and additional data modules are enabled, API response files can be large in size. To reduce bandwidth and limit your API result to return only the fields your application requires, you can specify one or multiple preferred response fields using the API's fields parameter.

Example:

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"

Example API Request:

https://api.positionstack.com/v1/forward
    ? access_key = YOUR_ACCESS_KEY
    & query = 1600 Pennsylvania Ave NW, Washington DC
    & fields = results.label,results.map_url

Example API Response:

As you can see below, the API returns a lightweight API response only containing the two specified fields.

{
   "label": "1600 Pennsylvania Avenue NW, Washington, DC, USA",
   "map_url": "http://map.positionstack.com/38.897675,-77.036547"
}

Specify Output Format Available on: Basic Plan and higher

By default, all geocoding results are returned in standard JSON format. For customers subscribed to the Basic Plan or higher, there is an additional output parameter that can be used to switch their preferred output format to XML or GeoJSON.

Example API Request:

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

Example API Response:

{
  "data": {
    "type": "FeatureCollection",
    "features": [
      {
        "type": "Feature",
        "geometry": {
          "type": "Point",
          "coordinates": [
            -77.036547,
            38.897675
          ]
        },
        "properties": {
          "name": "1600 Pennsylvania Avenue NW",
          "type": "address",
          "number": "1600",
          "street": "Pennsylvania Avenue NW",
          "postal_code": "20500",
          "confidence": 1,
          "region": "District of Columbia",
          "region_code": "DC",
          "neighbourhood": "White House Grounds",
          "country": {
            "latitude": "39.44325637817383",
            "longitude": "-98.95733642578125",
            "common_name": "United States",
            "official_name": "United States of America",
            "capital": "Washington D.C.",
            "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"
            }
          },
          "map_url": "http://map.positionstack.com/38.897675,-77.036547",
          "label": "1600 Pennsylvania Avenue NW, Washington, DC, USA"
        },
        "sun": {
          "rise": {
            "time": 1575461426,
            "astronomical": 1575455738,
            "civil": 1575459659,
            "nautical": 1575457670
          },
          "set": {
            "time": 1575495970,
            "astronomical": 1575501659,
            "civil": 1575497738,
            "nautical": 1575499726
          },
          "transit": 1575478698
        },
        "timezone": {
          "name": "America/New_York",
          "offset_sec": -18000,
          "offset_string": "-05:00"
        }
      }
    ]
  }
}

GeoJSON Specification: To learn more about GeoJSON and how it is used, please take a look at the following GeoJSON article.

Code Examples

The positionstack API is compatible with all major programming languages out there. Find below some straightforward code examples for forward geocoding in PHP, Python, Node.js, jQuery, Go and Ruby.


Code Examples - PHP

Forward Geocoding:

$queryString = http_build_query([
  'access_key' => 'YOUR_ACCESS_KEY',
  'query' => '1600 Pennsylvania Ave NW',
  'region' => 'Washington',
  'output' => 'json',
  'limit' => 1,
]);

$ch = curl_init(sprintf('%s?%s', 'https://api.positionstack.com/v1/forward', $queryString));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$json = curl_exec($ch);

curl_close($ch);

$apiResult = json_decode($json, true);

print_r($apiResult);

Reverse Geocoding:

$queryString = http_build_query([
  'access_key' => 'YOUR_ACCESS_KEY',
  'query' => '48.2084,16.3731',
  'language' => 'ES',
]);

$ch = curl_init(sprintf('%s?%s', 'https://api.positionstack.com/v1/reverse', $queryString));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$json = curl_exec($ch);

curl_close($ch);

$apiResult = json_decode($json, true);

print_r($apiResult);

Code Example - Python

Forward Geocoding:

# 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'))

Reverse Geocoding:

# Python 3
import http.client, urllib.parse

conn = http.client.HTTPConnection('api.positionstack.com')

params = urllib.parse.urlencode({
    'access_key': 'YOUR_ACCESS_KEY',
    'query': '51.507822,-0.076702',
    })

conn.request('GET', '/v1/reverse?{}'.format(params))

res = conn.getresponse()
data = res.read()

print(data.decode('utf-8'))

Code Example - Nodejs

Forward Geocoding:

const axios = require('axios');
const params = {
  access_key: 'YOUR_ACCESS_KEY',
  query: '1600 Pennsylvania Ave NW'
}

axios.get('https://api.positionstack.com/v1/forward', {params})
  .then(response => {
    console.log(response.data);
  }).catch(error => {
    console.log(error);
  });

Code Example - jQuery

Forward Geocoding:

$.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));
  });

Reverse Geocoding:

$.ajax({
    url: 'https://api.positionstack.com/v1/reverse',
    data: {
      access_key: 'YOUR_ACCESS_KEY',
      query: '51.507822,-0.076702',
      output: 'xml',
      limit: 1
    }
  }).done(function(data) {
    console.log(data);
  });

Code Example - Go

Forward Geocoding:

package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
)

func main() {
	baseURL, _ := url.Parse("https://api.positionstack.com")

	baseURL.Path += "v1/forward"

	params := url.Values{}
	// Access Key
	params.Add("access_key", "YOUR_ACCESS_KEY")
	// Query
	params.Add("query", "1600 Pennsylvania Avenue NW, Washington, DC, USA")
	// Optional parameters
	params.Add("region", "Washington")
	params.Add("output", "json")
	params.Add("limit", "1")

	baseURL.RawQuery = params.Encode()

	req, _ := http.NewRequest("GET", baseURL.String(), nil)

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()

	body, _ := ioutil.ReadAll(res.Body)

	fmt.Println(string(body))
}

Reverse Geocoding:

package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
)

func main() {
	baseURL, _ := url.Parse("https://api.positionstack.com")

	baseURL.Path += "v1/reverse"

	params := url.Values{}
	// Access Key
	params.Add("access_key", "YOUR_ACCESS_KEY")
	// Query = latitude,longitude
	params.Add("query", "51.507822,-0.076702")
	// Optional parameters
	params.Add("language", "fr")
	params.Add("output", "json")

	baseURL.RawQuery = params.Encode()

	req, _ := http.NewRequest("GET", baseURL.String(), nil)

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()

	body, _ := ioutil.ReadAll(res.Body)

	fmt.Println(string(body))
}


Code Example - Ruby

Forward Geocoding:

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


Reverse Geocoding:

require 'uri'
require 'net/http'

uri = URI('https://api.positionstack.com/v1/reverse')

params = {
    'access_key' => 'YOUR_ACCESS_KEY',
    'query' => '48.2084,16.3731',
    'language' => 'DE',
    'output' => 'json'
}

uri.query = URI.encode_www_form(params)

response = Net::HTTP.get_response(uri)

puts response.read_body


Business Continuity - API Overages

Ensuring our customers achieve success is paramount to what we do at APILayer. For this reason, we will be rolling out our Business Continuity plan guaranteeing your end users will never see a drop in coverage. Every plan has a certain amount of API calls that you can make in the given month. However, we would never want to cut your traffic or impact user experience negatively for your website or application in case you get more traffic.

What is an overage?

An overage occurs when you go over a quota for your API plan. When you reach your API calls limit, we will charge you a small amount for each new API call so we can make sure there will be no disruption in the service we provide to you and your website or application can continue running smoothly.

Prices for additional API calls will vary based on your plan. See table below for prices per call and example of an overage billing.

Plan Name Monthly Price Number of Calls Overage Price per call Overage Total price
Basic $9.99 100,000 0.00014985 10,000 $11.49
Professional $49.99 1,000,000 0.000074985 10,000 $50.74
Business $99.99 3,000,000 0.000049995 10,000 $100.49

Why does APILayer have overage fees?

Overage fees allow developers to continue using an API once a quota limit is reached and give them time to upgrade their plan based on projected future use while ensuring API providers get paid for higher usage.

How do I know if I will be charged for overages?

When you are close to reaching your API calls limit for the month, you will receive an automatic notification (at 75%, 90% and 100% of your monthly quota). However, it is your responsibility to review and monitor for the plan’s usage limitations. You are required to keep track of your quota usage to prevent overages. You can do this by tracking the number of API calls you make and checking the dashboard for up-to-date usage statistics.

How will I be charged for my API subscription?

You will be charged for your monthly subscription plan, plus any overage fees applied. Your credit card will be billed after the billing period has ended.

What happens if I don’t have any overage fees?

In this case, there will be no change to your monthly invoice. Only billing cycles that incur overages will see any difference in monthly charges. The Business Continuity plan is an insurance plan to be used only if needed and guarantees your end users never see a drop in coverage from you.

What if I consistently have more API calls than my plan allows?

If your site consistently surpasses the set limits each month, you may face additional charges for the excess usage. Nevertheless, as your monthly usage reaches a certain threshold, it becomes more practical to consider upgrading to the next plan. By doing so, you ensure a smoother and more accommodating experience for your growing customer base.

I would like to upgrade my plan. How can I do that?

You can easily upgrade your plan by going to your Dashboard and selecting the new plan that would be more suitable for your business needs. Additionally, you may contact your Account Manager to discuss a custom plan if you expect a continuous increase in usage.


Introducing Platinum Support - Enterprise-grade support for APILayer

Upgrade your APIlayer subscription with our exclusive Platinum Support, an exceptional offering designed to enhance your business’ API management journey. With Platinum Support, you gain access to a host of premium features that take your support experience to a whole new level.

What does Platinum Support include?

Standard Support Platinum Support
General review on the issue
Access to knowledge base articles
Email support communication
Regular products updates and fixes
Dedicated account team
Priority Email Support with unlimited communication
Priority bug and review updates
Option for quarterly briefing call with product Management
Features requests as priority roadmap input into product

Priority Email Support: Experience unrivaled responsiveness with our priority email support. Rest assured that your inquiries receive top-priority attention, ensuring swift resolutions to any issues.

Unlimited Communication: Communication is key, and with Platinum Support, you enjoy unlimited access to our support team. No matter how complex your challenges are, our experts are here to assist you every step of the way.

Priority Bug Review and Fixes: Bugs can be a headache, but not with Platinum Support. Benefit from accelerated bug review and fixes, minimizing disruptions and maximizing your API performance.

Dedicated Account Team: We understand the value of personalized attention. That's why Platinum Support grants you a dedicated account team, ready to cater to your specific needs and provide tailored solutions.

Quarterly Briefing Call with Product Team: Stay in the loop with the latest updates and insights from our Product team. Engage in a quarterly briefing call to discuss new features, enhancements, and upcoming developments.

Priority Roadmap Input: Your input matters! As a Platinum Support subscriber, your feature requests receive top priority, shaping our product roadmap to align with your evolving requirements.

Don't settle for the standard when you can experience the exceptional. Upgrade to Platinum Support today and supercharge your APIlayer experience!

xxx

xxx