Python programming API entry: (1) Use Baidu map API to check geographic coordinates

In network programming, we will deal with APIs. So, what is an API? How to use an API? This article shares my understanding of the API and the use of Baidu Map API.

API is the abbreviation of "Application Programming Interface". If a lot of terms and definitions make you dizzy, try to understand it like this: Internet service providers (such as Baidu, Weibo, etc.) have a lot of data, we can query the data, but we need to follow a certain format/protocol, otherwise The service provider does not know that our needs cannot be processed, and we cannot understand the data when we get it. Through the API interface specification, both communication parties can understand the information and data transmitted by the other party, and it also simplifies the operation (as long as the input is in the prescribed format, the output in the known format can be obtained. We don't need to know the technical details of the specific implementation, right? Very worry-free?)

The following is an example of calling Baidu Maps Web Service API .
Baidu Map API Platform

To use the "forward/reverse geocoding service" shown in the figure. Before using the service, you need to log in to your Baidu account (register one if you don't have one), apply to become a Baidu developer, and then create your own application to receive a corresponding service key (AK). On the service configuration page, there are two verification methods, one is the IP whitelist method, and the other is the sn verification method. According to the introduction in the article
Python Implementing Baidu Map API to Obtain the Longitude and Latitude
of an Address , I chose the sn verification method, so that there will be SK on the page. Please keep the two serial codes AK and SK. This is your personal verification information. The next step is to use Baidu Map API.

The function of this small Python program to be written is: input an address to get the corresponding latitude and longitude coordinate information . Implementation in three steps:

  1. Generate url (used to submit to API for query)
  2. Interact with API, query and return data (json format)
  3. Use json to parse and output.

The specific implementation is introduced below.

1. Sn code and url generation

url= http://api.map.baidu.com/geocoder/v2/?address="input location name"&output=json&ak='your AK code'&sn='your sn code'.
have to be aware of is:

  • Since there are Chinese strings in the URL, you need to use a function to urllib.parse.quote(inputstr, safe="/:=&?#+!$,;'@()*[]")convert the encoding.
  • In the url output, you can choose to output in json format or xml format. The default is xml format.
import urllib.request,urllib.parse,urllib.error
import json
import hashlib

MyAK='这里请填入你的AK'
MySK='这里请填入你的SK'

while True:
    address = input('输入地点:')
    if len(address)<1:
        break

    #产生sn码
    queryStr="/geocoder/v2/?address="+address+'&output=json&ak='+MyAK
    encodedStr=urllib.parse.quote(queryStr, safe="/:=&?#+!$,;'@()*[]")
    rawStr=encodedStr+MySK
    sn=(hashlib.md5(urllib.parse.quote_plus(rawStr).encode("utf8")).hexdigest())

    #生成url  
    url=urllib.parse.quote("http://api.map.baidu.com"+queryStr+"&sn="+sn,safe="/:=&?#+!$,;'@()*[]")
    print('Retrieving',url)

2. Enter url and use urllib to read data from API

    #从API读取数据
    uh=urllib.request.urlopen(url)
    data=uh.read().decode()
    print('Retrieved',len(data),'characters')

3. Use json to parse the returned data.

#解析数据
    try:
        js=json.loads(data)
    except:
        js=None

    if not js or 'status'not in js or js['status']!=0:
        print('======Failure====')
        print(data)
        continue
    print(json.dumps(js,indent=4,ensure_ascii=False))

The above code can output data in json format. For example, after entering "Baidu Building", the json format data output by the program is as follows:

{
    "status": 0,
    "result": {
        "location": {
            "lng": 116.30695597357376,
            "lat": 40.05738753357608
        },
        "precise": 1,
        "confidence": 80,
        "comprehension": 100,
        "level": "商务大厦"
    }
}

It should be noted here beginning Chinese characters "商务大厦"are not displayed correctly, I learned from the article python Chinese coding & json Chinese output problems found the answer in the json.dumps()function, the default converted to ASCII encoding, Chinese characters can not switch the display, so json.dumps()the To be set ensure_ascii=False.

Finally, through the following code, you can extract information such as latitude and longitude coordinates.

    #获取经纬度坐标和地址类型
    lat=js["result"]["location"]["lat"]
    lng=js["result"]["location"]["lng"]
    print('纬度',lat,'经度',lng)
    level=js["result"]["level"]
    print('地址类型',level)

Summary: Send the URL according to the specification and correctly parse the returned json or xml format data, and pay attention to the encoding of Chinese characters, you can get started with the API. how about it? Come and try it!

Welcome to continue reading my article:
Introduction to Python Programming API: (2) Using Sina Weibo API in Python3

Guess you like

Origin blog.csdn.net/applebear1123/article/details/103433233