如何使用python,json和google maps反转地理编码服务器端? [英] How to reverse geocode serverside with python, json and google maps?

查看:106
本文介绍了如何使用python,json和google maps反转地理编码服务器端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了服务器反向地理编码,可以让我得到一个json响应,现在我想从json响应中获得2或3个变量:



喜欢解析这个数据并以例如。
administrative_area_level_1 ='Stockholm'



jsondata = json.load(urllib2 .urlopen('http://maps.googleapis.com/maps/api/geocode/json?latlng=59.3,18.1&sensor=false'))



这里是我的python代码,它提取了json,现在我想知道如何解析它以获取


  • administrative_area_level_1 long_name(即州或地区名称)

  • 地点长名称(即城市名称)

  • 了解如何解析我的json



我可以解析它,但并不总是以administrative_area_1的形式出现:

jsondata [results] [0] [address_components] [5] [long_name]



上面的线正确地输出纽约在纽约的一个点,但是对于斯德哥尔摩它输出邮政城市,即不是administraive_area_1(地区/州)的Johanneshow。那么如何保证该函数总是返回administrative_area_1,最好不用循环?



我希望它可以像下面这样直接访问国家,地区和城市:

  logging.info(country:+ str(jsondata [results] [9] [formatted_address])) 
logging.info(administrative_area_level_1:+ str(jsondata [results] [8] [formatted_address]))
logging.info(locality:+ str(jsondata [results ] [8] [formatted_address]))

预先致谢

更新



这是我期望的结果,这是一个很好的答案。在等待答案的同时,我也尝试过自己实现一个解决方案,它似乎是这样做的:

  jsondata = json.load(urllib2。的urlopen( 'http://maps.googleapis.com/maps/api/geocode/json?latlng='+str(ad.geopt.lat)+', '+ STR(ad.geopt.lon)+' &安培;传感器= false'))
logging.info(geography:+ str(jsondata [results] [1] [formatted_address]))
region = None
city = None
for results in jsondata [results]:
#logging.info(result:+ str(result))
for result [address_components]:
logging.info(components:+ str(component))
logging.info(components type:+ str(component [types]))
如果组件中有'administrative_area_level_1' [types]:
#logging.info(unicode('found admin area:%s'%component [long_name]))
region = component [long_name]
如果组件[types中的'locality']:
logging.info(found locality:+ str(component [long_name]))
city = co mponent [long_name]





解决方案

处理响应



不需要解析JSON - 它已经被 json.load()并作为Python的数据结构返回。 像使用简单字典一样使用它,其中包含列表或不同的字典。



访问所需的响应部分



要访问您应该使用的数据,可以使用以下内容:

  jsondata ['results' ] [0] ['address_components'] 

其中地理名称包括:

lockquote
[u'route '],u'short_name':u'S\xf6dra L\xe4nken '},{u'long_name':u'Stockholm 'u'types ':[u'locality',u'political'] ,u'short_name ':u'Stockholm'},{u'long_name ':u'Stockholm',u'types ':[u'administrative_area_level_1',u'political '],u'short_name':u'Stockholm'} ,{u'long_name':u'Sweden',u'types':[u'country',u'political'],u'short_name':u'SE },{u'long_name ':u'12146',u'types ':[u'postal_code'],u'short_name ':u'12146'},{u'long_name ':u'Johanneshov',u'types ':[u'postal_town'],u'short_name':u'Johanneshov'}]




过滤需要的数据



正如你所看到的,有很多你不需要的数据,但你只需要 locality administrative_area_level_1 信息。您可以使用 filter() Python函数来过滤数据:

 >>> mydata = jsondata ['results'] [0] ['address_components'] 
>>> types = ['locality','administrative_area_level_1']
>>> geonames = filter(lambda x:len(set(x ['types'])。intersection(types)),mydata)

基本上,您只能在其类型列表中获取具有locality或administrative_area_level_1的元素。之后, geonames 将会包含您需要的字典列表:


[{ u'long_name':u'Stockholm',u'types':[u'locality',u'political'],u'short_name':u'Stockholm'},{u'long_name':u'Stockholm',u 'types':[u'administrative_area_level_1',u'political'],u'short_name':u'Stockholm'}]




显示数据



要显示他们的名字,您可以例如。遍历它们,显示 long_name s和相应的类型值:

 >>> geonames中的geoname:
common_types = set(geoname ['types'])。intersection(set(types))
print'{}({})'。format(geoname ['long_name']] ,str(','.join(common_types)))


斯德哥尔摩(地区)
斯德哥尔摩(administrative_area_level_1)
pre>

这是您的预期吗?



整码



代码可能如下所示:

  import json 
import urllib2

def get_geonames(lat,lng,types):
url ='http://maps.googleapis.com/maps/api/geocode/json'+ \
'?latlng = {}, {}&安培;传感器= false'.format(纬度,经度)
jsondata = json.load(urllib2.urlopen(URL))
address_comps = jsondata [ '结果'] [0] [address_components ']
filter_method = lambda x:len(set(x ['types'])。intersection(types))
return filter(filter_method,address_comps)

lat,lng = 59.3,18.1
types = ['locality', 'administrative_area_level_1']

#显示地名连同它们的类型
为geoname在get_geonames(纬度,经度,类型):
common_types =集(geoname [ '类型' ])。intersection(set(types))
print'{}({})'。格式(geoname ['long_name'],','.join(common_types))


I'm trying serverside reverse geocoding that can get me a json response and now I want to get 2 or 3 variables from the json response:

I'd like to parse for instance this data and end with eg. administrative_area_level_1 = 'Stockholm'

jsondata = json.load(urllib2.urlopen('http://maps.googleapis.com/maps/api/geocode/json?latlng=59.3,18.1&sensor=false'))

Here is my python code that fetches the json, now I wonder how to parse it to get just the

  • administrative_area_level_1 long_name (ie state or region name)
  • locality long name (ie city name)
  • an understanding how to parse my json

I can parse it but it is not always is comes out as administrative_area_1:

jsondata["results"][0]["address_components"][5]["long_name"]

The line above correctly outputs "New York" for a point in New York but for Stockholm it outputs a postal city ie Johanneshow which is not the administraive_area_1 (region/state). So how guarantee that the function always returns the administrative_area_1, preferably without looping?

I want it to work something like the following with direct access to country, region and city:

logging.info("country:"+str(jsondata["results"][9]["formatted_address"]))
logging.info("administrative_area_level_1:"+str(jsondata["results"][8]["formatted_address"]))
logging.info("locality:"+str(jsondata["results"][8]["formatted_address"]))

Thanks in advance

Update

It's a good answer here with the results I expected. While waiting for the answer I also tried implement a solution myself that seems to do it:

jsondata = json.load(urllib2.urlopen('http://maps.googleapis.com/maps/api/geocode/json?latlng='+str(ad.geopt.lat)+','+str(ad.geopt.lon)+'&sensor=false'))
logging.info("geography:"+str(jsondata["results"][1]["formatted_address"]))
region = None
city = None
for result in jsondata["results"]:
  #logging.info("result:"+str(result))
  for component in result["address_components"]:
    logging.info("components:"+str(component))
    logging.info("components type:"+str(component["types"]))
    if 'administrative_area_level_1' in component["types"]:
      #logging.info(unicode('found admin area:%s' % component["long_name"]))
      region = component["long_name"]
    if 'locality' in component["types"]:
      logging.info("found locality:"+str(component["long_name"]))
      city = component["long_name"]


解决方案

Processing the response

There is no need to parse the JSON - it is already parsed by json.load() and returned as Python's data structure. Use it like simple dictionary with lists or different dictionaries in it.

Accessing the needed part of the response

To access data you should be working with you can use the following:

jsondata['results'][0]['address_components']

which is where all information on geographical names is included:

[{u'long_name': u'S\xf6dra L\xe4nken', u'types': [u'route'], u'short_name': u'S\xf6dra L\xe4nken'}, {u'long_name': u'Stockholm', u'types': [u'locality', u'political'], u'short_name': u'Stockholm'}, {u'long_name': u'Stockholm', u'types': [u'administrative_area_level_1', u'political'], u'short_name': u'Stockholm'}, {u'long_name': u'Sweden', u'types': [u'country', u'political'], u'short_name': u'SE'}, {u'long_name': u'12146', u'types': [u'postal_code'], u'short_name': u'12146'}, {u'long_name': u'Johanneshov', u'types': [u'postal_town'], u'short_name': u'Johanneshov'}]

Filtering data you need

As you can see, there is plenty of data you do not need, but you want only locality and administrative_area_level_1 information. You can filter the data using filter() Python function like that:

>>> mydata = jsondata['results'][0]['address_components']
>>> types = ['locality', 'administrative_area_level_1']
>>> geonames = filter(lambda x: len(set(x['types']).intersection(types)), mydata)

Basically you are getting only elements that have 'locality' or 'administrative_area_level_1' in their "types" lists. After the above, geonames will be list containing dictionaries you need:

[{u'long_name': u'Stockholm', u'types': [u'locality', u'political'], u'short_name': u'Stockholm'}, {u'long_name': u'Stockholm', u'types': [u'administrative_area_level_1', u'political'], u'short_name': u'Stockholm'}]

Displaying the data

To display their names you can eg. iterate through them, displaying long_names and respective types values:

>>> for geoname in geonames:
    common_types = set(geoname['types']).intersection(set(types))
    print '{} ({})'.format(geoname['long_name'], str(', '.join(common_types)))


Stockholm (locality)
Stockholm (administrative_area_level_1)

Is this what you expected?

Whole code

The code could look like this:

import json
import urllib2

def get_geonames(lat, lng, types):
    url = 'http://maps.googleapis.com/maps/api/geocode/json' + \
            '?latlng={},{}&sensor=false'.format(lat, lng)
    jsondata = json.load(urllib2.urlopen(url))
    address_comps = jsondata['results'][0]['address_components']
    filter_method = lambda x: len(set(x['types']).intersection(types))
    return filter(filter_method, address_comps)

lat, lng = 59.3, 18.1
types = ['locality', 'administrative_area_level_1']

# Display all geographical names along with their types
for geoname in get_geonames(lat, lng, types):
    common_types = set(geoname['types']).intersection(set(types))
    print '{} ({})'.format(geoname['long_name'], ', '.join(common_types))

这篇关于如何使用python,json和google maps反转地理编码服务器端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆