Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The method of obtaining the distance between two places by using Baidu Map in Python

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the relevant knowledge of "Python uses Baidu map to obtain the distance between the two places", the editor shows you the operation process through the actual case, the operation method is simple, fast and practical. I hope that this "Python method of obtaining the distance between the two places using Baidu map" can help you solve the problem.

Baidu Map Open platform

After entering the Baidu Map Open platform, log in to the user, click the console above, follow the prompts to activate and create a server-type application, and set the application name arbitrarily, in which whitelist verification does not make any restrictions, you can enter 0.0.0.0max 0. After the creation is successful, the screen should be shown in the following figure, in which the access application (AK), that is, the part surrounded by the red box on the way, must be careful not to leak out at will. You need to use it later. This is a series of passwords needed for later access.

Introduce the API you need to use

All the API used in this project are Web service API, official development documents.

1. Location retrieval service

Location retrieval service (also known as Place API) is a kind of Web API interface service.

The service provides location (POI) retrieval functions for a variety of scenarios, including city retrieval, circular region retrieval and rectangular region retrieval. Developers can obtain basic or detailed geographic information of location (POI) through the interface.

We use this API to obtain two parameters of latitude and longitude (lat, lng) of the specified location.

two。 Batch routing service

The batch routing Service (aka RouteMatrix API) is a lightweight batch routing interface in the form of HTTP/HTTPS that allows users to calculate the planned distance and travel time based on the start and end coordinates. RouteMatrix API V2.0 supports Chinese mainland region.

We use this API to obtain the planned distance between two locations (given by latitude and longitude).

Write Python programs

0. Modules to be used

Requests

Json

1. Get the latitude and longitude of the corresponding location

The longitude and latitude of the incoming address are obtained through the location retrieval service, and the return value is the string value corresponding to the latitude and longitude, separated by a comma, and then returned with a query. If the query fails, the status value is not 0.

Note that the AK in the code is replaced with the AK code in the initial screenshot.

Def getPosition (address): url = r "http://api.map.baidu.com/place/v2/search?query={}®ion= National & output=json&ak= {}" .format (address AK # here is the first screenshot circled in red) res = requests.get (url) json_data = json.loads (res.text) if json_data ["status"] = 0: lat = json_data ["results"] [0] ["location"] ["lat"] # Latitude lng = json_data ["results"] [0] ["location"] ["lng"] # Longitude else: print ("[ERROR] Can not find {}." .format (address)) return "0Pol 0" Json_data ["status"] return str (lat) + "," + str (lng), json_data ["status"] 2. Get the distance between the two places

The route planning distance between the two incoming locations (described in latitude and longitude) is obtained through the batch routing service. This example is calculated by driving (the corresponding parameter is "driving").

Also note that the AK in the code is replaced with the AK code in the initial screenshot.

Def getDistance (start, end): url = "http://api.map.baidu.com/routematrix/v2/driving?output=json&origins={}&destinations={}&ak={}".format( start, end, AK # here is the first screenshot circled in red) res = requests.get (url) content = res.content jsonv = json.loads (str (content) "utf-8") dist = jsonv ["result"] [0] ["distance"] ["value"] return dist3. Merge function calls

Pass in the names of two places and return the distance between them. When a location cannot be queried, the return result will be set to-1.

Def calcDistance (startName, endName): start, status1 = getPosition (startName) end, status2 = getPosition (endName) if status1 = 0 and status2 = 0: return getDistance (start, end) else: return-14. Perform a simple functional test

The running code outputs the distance between Beijing and Chengdu, in meters.

5. Calculate the distance for batch locations in Excel

Read all the locations in the data.xlsx file and calculate the distance, and save the result to the local result.xlsx file, where we set the unit of distance to kilometer. The code of the main module is as follows:

If _ _ name__ = = "_ main__": data = pd.read_excel ("data.xlsx") res = [] for i in range (0, len (data)): startName = data.iloc [I, 0] endName = data.iloc [I, 1] dist = calcDistance (startName, endName) res.append ([startName, endName) Dist / 1000]) pd.DataFrame (res) .to_excel ("result.xlsx", header= ["start", "end", "distance"], index=None, encoding= "utf-8")

The content of the data.xlsx file is:

The corresponding output result.xlsx file is as follows:

Appendix

# the overall source code AK = "modify your own AK code to use" import pandas as pdimport requestsimport jsondef getPosition (address): url = r "http://api.map.baidu.com/place/v2/search?query={}®ion= National & output=json&ak= {}" .format (address AK # here is the first screenshot circled in red) res = requests.get (url) json_data = json.loads (res.text) if json_data ["status"] = 0: lat = json_data ["results"] [0] ["location"] ["lat"] # Latitude lng = json_data ["results"] [0] ["location"] ["lng"] # Longitude else: print ("[ERROR] Can not find {}." .format (address)) return "0Pol 0" Json_data ["status"] return str (lat) + "," + str (lng), json_data ["status"] def getDistance (start, end): url = "http://api.map.baidu.com/routematrix/v2/driving?output=json&origins={}&destinations={}&ak={}".format( start, end AK # here is the first screenshot circled in red) res = requests.get (url) content = res.content jsonv = json.loads (str (content, "utf-8")) dist = jsonv ["result"] [0] ["distance"] ["value"] return distdef calcDistance (startName, endName): start, status1 = getPosition (startName) end Status2 = getPosition (endName) if status1 = 0 and status2 = 0: return getDistance (start, end) else: return-1if _ name__ = = "_ _ main__": data = pd.read_excel ("data.xlsx") res = [] for i in range (0, len (data): startName = data.iloc [I, 0] endName = data.iloc [I, 1] dist = calcDistance (startName) EndName) res.append ([startName, endName, dist / 1000]) pd.DataFrame (res). To_excel ("result.xlsx", header= ["starting point", "end point", "distance"], index=None, encoding= "utf-8") this is the end of the introduction to "Python's method of obtaining the distance between two places using Baidu Map" Thank you for your reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report