how to convert from longitude and latitude to country or city?

后端 未结 5 1740
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-31 03:51

I need to convert longitude and latitude coordinates to either country or city, is there an example of this in python?

thanks in advance!

5条回答
  •  孤城傲影
    2021-01-31 04:57

    Google has since depreciated keyless access to their API. Head over to google and register for a key, you get ~ 1,000 free queries a day. Code in accepted answer should be modified like this (can't add a comment, not enough rep).

    from urllib.request import urlopen
    import json
    
    def getplace(lat, lon):
        key = "yourkeyhere"
        url = "https://maps.googleapis.com/maps/api/geocode/json?"
        url += "latlng=%s,%s&sensor=false&key=%s" % (lat, lon, key)
        v = urlopen(url).read()
        j = json.loads(v)
        components = j['results'][0]['address_components']
        country = town = None
        for c in components:
            if "country" in c['types']:
                country = c['long_name']
            if "postal_town" in c['types']:
                town = c['long_name']
    
        return town, country
    
    print(getplace(51.1, 0.1))
    print(getplace(51.2, 0.1))
    print(getplace(51.3, 0.1))
    

提交回复
热议问题