Skip to content

Instantly share code, notes, and snippets.

@mnguyenngo
Created September 3, 2018 22:23
Show Gist options
  • Save mnguyenngo/d8761679e7ae75bb46bc7e9df3921e5f to your computer and use it in GitHub Desktop.
Save mnguyenngo/d8761679e7ae75bb46bc7e9df3921e5f to your computer and use it in GitHub Desktop.
Working with geocoding APIs

Working with Geocoding APIs

This document will contain the syntax for working with various geocoding APIs

Google Maps

Documentation: https://developers.google.com/maps/documentation/maps-static/dev-guide API URL: https://maps.googleapis.com/maps/api/geocode/json

Get Coordinates from Address

import requests
import time
import yaml


def get_latlon(address, return_latlon_only=True, lag=2):
    """Use Google Map's Geocoding API to return latitude and longitude when
    given an address

    Arguments:
        address (str)
        return_latlon_only (bool): True (default); returns full output from
            Google API if False

    Returns:
        latitude (float)
        longitude (float)
    """
    time.sleep(lag)  # wait 1 seconds before each request

    geo_api = 'https://maps.googleapis.com/maps/api/geocode/json'

    with open("secrets/googlemaps_apikey.yaml", 'r') as f:
        try:
            credentials = yaml.load(f)
        except yaml.YAMLError as exc:
            print(exc)

    api_key = credentials['API_key']

    geo_params = {
        'address': address,
        'api_key': api_key
    }

    response = requests.get(geo_api, params=geo_params)

    if response.status_code == 200:
        if return_latlon_only:
            results = latlon = response.json()['results']
            if len(results) > 0:
                latlon = results[0]['geometry']['location']
                return latlon['lat'], latlon['lng']
            else:
                print(f"{response.status_code}: But index error?")
                return None, None
        else:
            return response.json()
    else:
        print(f"{response.status_code}: Could not return lat and lon results.")
        return None

HERE

Geocoder

Documentation: https://developer.here.com/documentation#geocoder Geocoder API: https://geocoder.api.here.com/6.2/geocode.json

>>> here_rest_api = "https://geocoder.api.here.com/6.2/geocode.json"

>>> geo_params = {
        'app_id': app_id,
        'app_code': app_code,
        'searchtext': '425 W Randolph Chicago'
    }

>>> response = requests.get(here_rest_api, params=geo_params)

>>> response.json()
# Returns JSON object with relevant map information

Reverse Geocoder

Documentation: https://developer.here.com/api-explorer/rest/geocoder/reverse-geocode Reverse Geocoding URL: https://reverse.geocoder.api.here.com/6.2/reversegeocode.json

>>> here_reverse_rest_api = "https://reverse.geocoder.api.here.com/6.2/reversegeocode.json"

>>> geo_params = {
        'app_id': app_id,
        'app_code': app_code,
        'prox': '47.625701, -122.365459, 10',
        'mode': 'retrieveLandmarks'
    }

>>> response.json()
# Returns nearby landmarks to given coordinates

Map Image

Map Image API URL: https://image.maps.api.here.com/mia/1.6/mapview

>>> here_map_image_api = "https://image.maps.api.here.com/mia/1.6/mapview"

>>> map_params = {
      'app_id': app_id,
      'app_code': app_code,
      'ppi': 72,
      'sb': 'km',
      'w': 100,
      'h': 100,
      'z': 12,
      'c': '47.625701,-122.365459',
      'style': 'alps'
    }

>>> response = requests.get(here_map_image_api, params=map_params)

>>> response.url
'https://image.maps.api.here.com/mia/1.6/mapview?app_id=FwXHrv2vtKomTN5h6S7z&app_code=GuSHrB83PPJl3ptbzquZyQ&ppi=72&sb=km&w=100&h=100&z=12&c=47.625701%2C-122.365459&style=alps'
# Go to the url above to see the image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment