2012-10-17 104 views

回答

2

您可以使用地圖API。我已經添加了一個片段,用於計算使用Postgis和Django轉換爲PointField的馬拉松起點。這應該讓你在路上。

import requests 

def geocode(data): 
    url_list = [] 
    for item in data: 
     address = ('%s+%s' % (item.city, item.country)).replace(' ', '+') 
     url = 'http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false' % address 
     url_list.append([item.pk, url]) 

    json_results = [] 
    for url in url_list: 
     r = requests.get(url[1]) 
     json_results.append([url[0], r.json]) 

    result_list = [] 
    for result in json_results: 
     if result[1]['status'] == 'OK': 
      lat = float(result[1]['results'][0]['geometry']['location']['lat']) 
      lng = float(result[1]['results'][0]['geometry']['location']['lng']) 
      marathon = Marathon.objects.get(pk=result[0]) 
      marathon.point = GEOSGeometry('POINT(%s %s)' % (lng, lat)) 
      marathon.save() 

    return result_list 
+0

乾杯,但我是從Lat&Long(作爲輸入)得到「Address」(作爲輸出)之後。你的例子與我想要的相反。我使用了類似的方法https://maps.googleapis.com/maps/api/geocode/json?latlng= – Ernest

+1

而不是地址,使用您的lat long值並檢查傳入的json結果。你會在那裏找到地址。 – super9

5

解決方案 - 調用此URL並解析它的JSON。

http://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&sensor=false 
3

使用geopy,它可以處理多個geocoders,包括googlev3。

from geopy.geocoders import GoogleV3 
geolocator = GoogleV3() 
location = geolocator.reverse("52.509669, 13.376294") 
print(location.address) 
>>> Potsdamer Platz, Mitte, Berlin, 10117, Deutschland, European Union 

安裝與PIP:

pip install geopy 

相關信息發現:https://github.com/geopy/geopy

+1

我使用相同的代碼,但使用時 打印(location.address)得到了一個錯誤 回溯(最近通話最後一個): 文件「」,1號線,在 AttributeError的:「名單」對象有沒有屬性「地址' –

+0

調用反向時,我得到了同樣的東西,座標列表 –

1

@rawsix答案似乎對於智能Django的用戶。 但請注意,由geolocator.reverse(query)返回的位置是一個列表,而不是一個Location對象;所以試圖從中檢索屬性address會導致錯誤。

通常,該列表中的第一項具有最近的地址信息。你還是你可以簡單地做:

location = location[0] 
address = location.address 

另外,除了傳遞字符串經緯向相反的方法,你可以使用一個元組,它必須是longitudelatitude。你可以這樣做:

from geopy.geocoders import GoogleV3() 
geocoder = GoogleV3() 
location_list = geocoder.reverse((latitude, longitude)) 
location = location_list[0] 
address = location.address