简体   繁体   中英

Geolocation get country name

I was wondering if there is a simple way to retrive the country name of the given city.

Meaning that I will provide the city name and it will give me back the country.

For now the only thing I can think of is reversegeo, but it only gives me the short for the country and I need the full name.

def reverseGeocode(coordinates):
    result = rg.search(coordinates,mode=1)
    print(result)
    
cord= (36.8968908,30.7133233)
reverseGeocode(cord)

Results:

[{'lat': '36.90812', 'lon': '30.69556', 'name': 'Antalya', 'admin1': 'Antalya', 'admin2': '', 'cc': 'TR'}]

Is there anyway to do it? or maybe to get the full name somehow?

I kept searching for the best way to do that and I found something that I will like to share with others we wants the same as me.

https://pypi.org/project/geocoder/

All I add to do is to install the library

pip install geocoder
import geocoder as rg
def reverseGeocode(coordinates):
    result = rg.osm(coordinates, method='reverse')
    print(result.json['country'])

I built a function and now you can call it with the lat,lng values.

cord= (36.8968908,30.7133233)
reverseGeocode(cord)

The only problem is that you will get the country name by the country language.

EDIT: Found the best solution.

import googlemaps as gm
def reverseGeocode(cords):
    gmaps = gm.Client(key=api)
    res = gmaps.reverse_geocode(cords)
    country = res[-1]['address_components'][0]['long_name']
    return country

cord = (lat,lng)
reverseGeocode(cord)

Works perfect.

A solution using reverse_geocode :

import reverse_geocode

coordinates = (36.8968908,30.7133233),
print(reverse_geocode.search(coordinates))

coordinates must be iterable, hence the , after the coordinates, to make the variable into a tuple.

Output:

[{'country_code': 'TR', 'city': 'Kepez', 'country': 'Turkey'}]

reverse_geocode needs to download a file once, so it's not completely offline, but once the file is downloaded the code should work even without an inte.net connection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM