Hacktoberfest Pay off

I looked up reverse geocoding with openstreetmap and found a keyless api. Reverse geocoding is the process of turning a location as a latitude and longitude into a place name. This is handy for creating my daily post footer, I want to have a script that will take in a lat/lng pair and output the full location name and weather with a map link.

I can use the kindly provided nominatim reverse geocoding URI and a bit of python. I guess openstreetmap thinks I am in a weird parallel UK that is made up of states, that is easy to deal with thankfully.

base_url = "http://nominatim.openstreetmap.org/reverse?format=json&lat={}&lon={}&zoom=18&addressdetails=1"
uri = base_url.format(lat, lng)

fp = urllib.request.urlopen(uri)
response = fp.read()

location = json.loads(response.decode("utf8"))
fp.close()

city = location['address']['city']
country = location['address']['country']

if country == "UK" or country == "US":
    country = location['address']['state']

return {'country':country, 'city':city}

I end up with a single script for generating the location/weather block. The script will default my 'work' location or it will try and format a lat/lng out of any arguments passed in.

#!/usr/bin/env python3.5

import forecastio
import pprint
import urllib.request
import json 
import sys

api_key = "yer_key_here_bawbag"
lat = 57.168
lng = -2.1055

def forwardweather(lat, lng):
    forecast = forecastio.load_forecast(api_key, lat, lng)

    weather = forecast.daily().data[0]

    temperatureMax = int(weather.apparentTemperatureMax)
    temperatureMin = int(weather.apparentTemperatureMin)
    summary = weather.summary

    return {'temperature':temperatureMax, 'summary':summary}

def reversegeocode(lat, lng):
    base_url = "http://nominatim.openstreetmap.org/reverse?format=json&lat={}&lon={}&zoom=18&addressdetails=1"
    uri = base_url.format(lat, lng)

    fp = urllib.request.urlopen(uri)
    response = fp.read()

    location = json.loads(response.decode("utf8"))
    fp.close()

    city = location['address']['city']
    country = location['address']['country']

    if country == "UK" or country == "US":
        country = location['address']['state']

    return {'country':country, 'city':city}

if __name__ == "__main__":
    if len(sys.argv) == 2:
        loc = sys.argv[1].split(',') 
        if len(loc) != 2:
            exit()
        lat = float(loc[0])
        lng = float(loc[1])
    if len(sys.argv) == 3:
        lat = float(sys.argv[1])
        lng = float(sys.argv[2])

    print("Getting weather for: {}, {}\n\n".format(lat, lng))

    weather = forwardweather(lat, lng)
    location = reversegeocode(lat, lng)

    base_url = "http://www.openstreetmap.org/search?query={}%2C%20{}"
    uri = base_url.format(lat, lng)

    print("[{}, {}][0]: {}°C, {}".format(location['city'], location['country'], 
        weather['temperature'], weather['summary']))
    print("\n[0]: {}".format(uri))

Reading: Virtual Light