Home  >  Article  >  Backend Development  >  How to use Baidu Map API to implement city search function by writing a program in Python?

How to use Baidu Map API to implement city search function by writing a program in Python?

WBOY
WBOYOriginal
2023-07-30 19:13:181393browse

How to write a program in Python and use Baidu Map API to implement city search function?

Baidu Map is a widely used map service that provides powerful location search and navigation functions. For developers, using Baidu Map API can easily implement geographical location-related functions in their own programs. This article will introduce how to use Python to write programs and use Baidu Map API to implement city search functions.

First, we need to register a Baidu Maps developer account and apply for an API key. Create an application on the Baidu Map open platform, and then obtain the corresponding AK (Access Key). This AK will be used in the program to send HTTP requests to obtain data.

Next, we need to install Python’s requests library, which is used to send HTTP requests and obtain the returned data. You can use the following command to install the requests library:

pip install requests

Now, we can start writing programs. First, import the necessary libraries:

import requests
import json

Then, define a function to send an HTTP request to obtain city search results. This function receives a city name as a parameter and returns a JSON string of city search results.

def city_search(city):
    url = "https://api.map.baidu.com/place/v2/search"
    params = {
        "query": city,
        "region": "中国",
        "output": "json",
        "ak": "你的AK"
    }
    response = requests.get(url, params=params)
    return response.text

The url here is the city search interface address of Baidu Map API, and params are the request parameters. Among them, query represents the search keyword, region represents the search area, output represents the returned data format, and ak is the AK we applied for before.

Next, we define a function to parse the JSON string of city search results and print out the name and address of each search result.

def parse_results(results):
    json_result = json.loads(results)
    if json_result["status"] == 0:
        for item in json_result["results"]:
            name = item["name"]
            address = item["address"]
            print(f"名称:{name},地址:{address}")
    else:
        print("查询失败")

Here, we first parse the JSON string into a Python object, and then determine the status of the returned result. If the status is 0, it means the query is successful, we iterate through each search result and get the name and address to print. If the status is not 0, the query fails and the corresponding prompt message is printed.

Finally, we define a main function to obtain the city name entered by the user, and call the above two functions to implement the city search function.

def main():
    city = input("请输入城市名称:")
    results = city_search(city)
    parse_results(results)

if __name__ == "__main__":
    main()

In the main function, we first obtain the city name entered by the user, then call the city_search function to send an HTTP request to obtain the search results, and finally call the parse_results function to parse and print the results.

So far, we have completed all the code to implement the city search function by writing programs in Python and using Baidu Map API.

To sum up, it is not complicated to write a program using Baidu Map API and Python to implement the city search function. By sending an HTTP request to obtain the JSON string of the city search results, we can use Python's json library to parse it and extract key information for display. I hope this article is helpful to you, and I wish you success in developing using Baidu Map API!

The above is the detailed content of How to use Baidu Map API to implement city search function by writing a program in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn