How to cancel server geocoding using python, json and google maps?

I am trying to use reverse geocoding with servers that can give me a json response, and now I want to get 2 or 3 variables from a json response:

I would like to analyze, for example, this data and complete, for example. 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 json retrieves, now I am wondering how to parse it, to only get

  • administrator_area_level_1 long_name (i.e. state or region name)
  • local name (e.g. city name)
  • understanding how to parse my json

I can parse it, but it does not always appear as administrator_area_1:

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

The line above correctly displays β€œNew York” for a point in New York, but for Stockholm it displays a postal city, i.e. Johanneshow, who is not an administrator_area_1 (region / state). So, how to guarantee that the function always returns administrative_are_1, preferably without a loop?

I want him to work with the following: with direct access to the 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

This is a good answer here with the expected results. While waiting for an answer, I also tried to implement a solution that seems to do this:

 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"] 

+6
source share
1 answer

Response processing

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

Access to the necessary part of the answer

To access the data you must work with, you can use the following:

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

where is all the information about geographical names :

[{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 the data you need

As you can see, there is a lot of data that you do not need, but you only need the locality and administrative_area_level_1 tags. You can filter data using the Python filter() function as follows:

 >>> 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 get only those elements that have "locality" or "Administrative_area_level_1" in their lists of "types". After the above, geonames will contain a list of dictionaries that 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'}]

Data display

To display their names, you can, for example. iterate through them, displaying the long_name and corresponding 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 might 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)) 
+13
source

Source: https://habr.com/ru/post/903163/


All Articles