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

后端 未结 5 1744
爱一瞬间的悲伤
爱一瞬间的悲伤 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:56

    In general the Google API is the best approach. It was not suitable for my case as I had to process a lot of entries and the api is slow.

    I coded a small version that does the same but downloads a huge geometry first and computes the countries on the machine.

    import requests
    
    from shapely.geometry import mapping, shape
    from shapely.prepared import prep
    from shapely.geometry import Point
    
    
    data = requests.get("https://raw.githubusercontent.com/datasets/geo-countries/master/data/countries.geojson").json()
    
    countries = {}
    for feature in data["features"]:
        geom = feature["geometry"]
        country = feature["properties"]["ADMIN"]
        countries[country] = prep(shape(geom))
    
    print(len(countries))
    
    def get_country(lon, lat):
        point = Point(lon, lat)
        for country, geom in countries.iteritems():
            if geom.contains(point):
                return country
    
        return "unknown"
    
    print(get_country(10.0, 47.0))
    # Austria
    

提交回复
热议问题