Python for Infomatics 13th page Service Four (translated)

Source: Internet
Author: User

These days because of other affairs, interrupted their own study plan, today continue my translation, to avoid the halfway and waste.

Note: The original article is Dr. Charles Severance's "Python for Informatics". The code in this article is rewritten with version 3.4 and passed in the native test.

13.7 Google's geocoding Web services

Google Inc. has a very good web service called geocoding. This service allows us to use their vast geographic information database. When we submit an "Ann Arbor, MI" location to the Geocoding API to find the string, Google will return it to speculate on the best location on the map to find the search string and tell us about the landmarks around.

The Geocoding Web service is free, but it limits the rate to prevent the profit-making process from using the API without restriction. If you have some survey data that is used by end users to enter location information in a free-form input box, you can use this API to organize your data nicely.

When you use a free API like Google geocoding, you need to respect the use of these resources. If too many people abuse the service, Google may stop or significantly reduce its free service.

You can read the online documentation for this service, but it is very simple and you even enter the following URL in your browser to test it.
Http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=Ann+Arbor%2C+MI

Before copying and pasting this URL into your browser, make sure to unpack and delete any spaces in the middle.
The following simple program prompts the user to enter a search string, then invokes the geocoding API and fetches the information from the returned JSON.
  

Importurllib.requestImportUrllib.parseImportJsonserviceurl='Http://maps.googleapis.com/maps/api/geocode/json?' whiletrue:address= Input ('Enter Location:')    ifLen (address) < 1 :         BreakURL= Serviceurl + Urllib.parse.urlencode ({'sensor':'false','Address': Address}) Print('receiving', URL)Try: Uh=urllib.request.urlopen (URL)except:        Print('Can not connect the server')         BreakData=Uh.read ()Print('Received', Len (data),'characters')    Try: JS= Json.loads (Data.decode ('Utf-8'))    except: JS="'    if 'Status'  not inchJsorjs['Status'] !='OK':        Print('= = = Failure to Retriev = = =')        Print(Data.decode ('Utf-8'))        Continue    Print(Json.dumps (js, indent = 4)) Lat= js["Results"][0]["Geometry"][" Location"]["lat"] LNG= js["Results"][0]["Geometry"][" Location"]["LNG"]    Print('lat', LAT,'LNG', LNG) location= js['Results'][0]['formatted_address']    Print(location)

This program obtains the lookup string first, then creates a URL, encodes the string appropriately as an argument in the URL, and then uses Urllib to obtain textual information from the Geocoding API. The data we get depends on the parameters we send and the data stored in Google instead of a fixed page.

Once we get the JSON data, we can use the JSON library to parse it and do some testing to make sure we get the right data, and then we crawl the data we're looking for.

The output of the program is as follows:

Enter location:chinareceiving http:maps.googleapis.com/maps/api/geocode/json?sensor=false&address=chinareceived1182characters{"Results": [        {            "formatted_address":" China",            "Types": [                "Country",                "political"            ],            "address_components": [                {                    "Types": [                        "Country",                        "political"                    ],                    "Long_name":" China",                    "Short_name":"CN"                }            ],            "Geometry": {                "Viewport": {                    "Southwest": {                        "lat": 18.1576156,                        "LNG": 73.4994136                    },                    "Northeast": {                        "lat": 53.56097399999999,                        "LNG": 134.7728099                    }                },                "Location_type":"approximate",                "bounds": {                    "Southwest": {                        "lat": 18.1576156,                        "LNG": 73.4994136                    },                    "Northeast": {                        "lat": 53.56097399999999,                        "LNG": 134.7728099                    }                },                " Location": {                    "lat": 35.86166,                    "LNG": 104.195397                }            },            "place_id":"Chijwulg5wsouderbzafnhyqhzu"        }    ],    "Status":"OK"}lat35.86166 LNG 104.195397 China

You can download geojson.py and geoxml.py from Www.py4inf.com/code, and explore the differences between the Google geocoding API JSON format and the XML format.

(Translator Note: Because of international export congestion reasons, access to geocoding API low success rate, need to try several times)

Python for Infomatics 13th page Service Four (translated)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.