使用Google API查找附近的城市

时间:2018-11-19 09:54:16

标签: python google-maps-api-3 django-rest-framework google-places-api

我想通过纬度和经度获得附近的城市。我曾经使用过地理名称和地理字节API,但想使用Google API查找附近的城市。

这是我的代码:

def getNearbyCities(self):
    # lat, lon = self.getLatLon()
    # res_url = urlopen('http://gd.geobytes.com/GetNearbyCities?callback=?&radius=100&limit=100&Latitude=' + str(lat) + '&Longitude=' + str(lon))
    res_url = urlopen('http://getnearbycities.geobytes.com/GetNearbyCities?callback=?&radius=100&locationcode=' + str(self.city))

    resp = str(res_url.read())
    print(resp)
    validate_res = resp.split("b'?(")[-1].split(");'")[0]
    validated_res = ast.literal_eval(validate_res)

    cities_nd_distence = []
    for data in validated_res:
        data_tuple = (data[1], data[7])
        if data[1] not in cities_nd_distence:
            cities_nd_distence.append(data_tuple)
    import pprint
    pprint.pprint(cities_nd_distence)
    return cities_nd_distence

1 个答案:

答案 0 :(得分:0)

如果您只想基于经度和纬度获取城市,可以看看https://github.com/coderholic/django-cities

from cities.models import City                                                                                

from django.contrib.gis.geos import Point                                                                     

from django.contrib.gis.db.models.functions import Distance                                                   

p = Point(-118, 34, srid=4326)                                                                                

City.objects.annotate(distance=Distance('location', p)).order_by("distance").first()                          

<City: Hacienda Heights>

enter image description here