Traffic accessibility analysis based on Baidu map API python

Keywords: Python api gis

1, What is traffic accessibility?

The most important consideration of traffic accessibility is traffic cost, that is, traffic distance and traffic time.
You can use the path planning service function of API to select the bus route and obtain the traffic time and distance between the two locations. The rule is to initiate a retrieval request in the form of http/https, transfer the coordinates of the two locations to Baidu map server, and the server returns the path planning results after calculation. Select distance and duration from the returned parameters to represent the total traffic network distance and total traffic travel time respectively.

Case description:
For example, if we want to calculate the bus accessibility of Shanghai Disneyland, we can first divide Shanghai into 500m*500m grids, then take the longitude and latitude of the grid as the starting point and the longitude and latitude of Disneyland as the end point, calculate the time and distance of the end point through Baidu map API, and then use GIS analysis tools to visualize the results on the map, The following accessibility map can be generated.

This article mainly introduces how to use Baidu API to calculate the real travel time and distance between two points.

2, Calculation steps

1. Import and storage

The code is as follows (example):

import requests
import json
import time

2. Call Baidu API to query the path between two points

If the amount of query data is large, the server sometimes drops the line, so the function of waiting and trying to connect again is done.
The code is as follows (example):

def getjson(ocoo,dcoo):
    # Latitude before longitude
    url='http://api.map.baidu.com/direction/v2/driving?origin='+ocoo+'&destination='+dcoo+'&coord_type=wgs84&departure_time=1595548800&tactics_incity=4&ak=XXX'
    while True:
        try:
            response=requests.get(url=url,timeout=5)
            break
        except requests.exceptions.ConnectionError:
            print ('ConnectionError -- please wait 3 sec')
            time.sleep(3)
        except requests.exceptions.ChunkedEncodingError:
            print ('ChunkedEncodingError -- please wait 3 sec')
            time.sleep(3)
        except:
            print ('Unknow error')
            time.sleep(3)
    html=response.text
    decodejson=json.loads(html)
    return decodejson

3. Enter the file to be calculated and the path to save the result file

Save the location attributes of the two points to be queried to a text file in the format of

Record numberStarting longitudeStarting latitudeEnd longitudeEnd latitude
1113.837522.8075113.827522.8175
2113.837522.5655113.887522.4626
3113.837522.1658113.873222.1235
...............
# Enter the path to the query file
file_object=open(r'D:\input\fromsz_base202011.csv','r')
# Save path of output result file
file_object2=open(r'D:\fromsz_base_dis202011.txt','w')

4. Read the file and calculate the time and distance

try:
    for line in file_object:
        count=count+1
        spline=line.split(',')
        idn=spline[0]
        coor=spline[5].strip()+','+spline[4].strip()
        door=spline[7].strip()+','+spline[6].strip()
        #print coor
        decodejson=getjson(coor,door)
        if decodejson.get('status')==0:#Indicates successful operation
            result=decodejson.get('result')
            routes=result.get('routes')
            #Get the time and distance you need
            if len(routes)>0:     
                time2=routes[0].get('duration')
                distance=routes[0].get('distance')
                file_object2.write(str(idn)+','+str(time2)+','+str(distance) +'\n')
                if count%10==0:
                    finishtime=time.asctime( time.localtime(time.time()))
                    finishtime1=time.time()
                    print (count)
                    print ('duration:',(finishtime1-starttime1)/60.0,'mins')
        else:
            print (str(coor)+','+ str(decodejson.get('status'))+decodejson.get('message'))

5. Code overview

# -*- coding: utf-8 -*-
# @Author: Xie 
# @Date:   2021-04-15 11:49:25
# @Last Modified by:   Xie 
# @Last Modified time: 2021-04-15 11:58:10


import requests
import json
import time
starttime=time.asctime(time.localtime(time.time()))   
starttime1=time.time();
# Call Baidu API to query the path between two points
def getjson(ocoo,dcoo):
    # Latitude before longitude
    url='http://api.map.baidu.com/direction/v2/driving?origin='+ocoo+'&destination='+dcoo+'&coord_type=wgs84&departure_time=1595548800&tactics_incity=4&ak=XXX'
    while True:
        try:
            response=requests.get(url=url,timeout=5)
            break
        except requests.exceptions.ConnectionError:
            print ('ConnectionError -- please wait 3 sec')
            time.sleep(3)
        except requests.exceptions.ChunkedEncodingError:
            print ('ChunkedEncodingError -- please wait 3 sec')
            time.sleep(3)
        except:
            print ('Unknow error')
            time.sleep(3)
    html=response.text
    decodejson=json.loads(html)
    return decodejson
# Enter the path to the query file
file_object=open(r'D:\input\fromsz_base202011.csv','r')
# Enter the path to save the result file
file_object2=open(r'D:\fromsz_base_dis202011.txt','w')
count=0
try:
    for line in file_object:
        count=count+1
        spline=line.split(',')
        idn=spline[0]
        coor=spline[5].strip()+','+spline[4].strip()
        door=spline[7].strip()+','+spline[6].strip()
        #print coor
        decodejson=getjson(coor,door)
        if decodejson.get('status')==0:#Indicates successful operation
            result=decodejson.get('result')
            routes=result.get('routes')
            #Get the time and distance you need
            if len(routes)>0:     
                time2=routes[0].get('duration')
                distance=routes[0].get('distance')
                file_object2.write(str(idn)+','+str(time2)+','+str(distance) +'\n')
                if count%10==0:
                    finishtime=time.asctime( time.localtime(time.time()))
                    finishtime1=time.time()
                    print (count)
                    print ('duration:',(finishtime1-starttime1)/60.0,'mins')
        else:
            print (str(coor)+','+ str(decodejson.get('status'))+decodejson.get('message'))
finally:
        file_object.close()
        file_object2.close()
        print ('finish')

summary

The above is the method of reachability calculation using map API, which is simple, user-friendly and accurate.
The traditional GIS accessibility calculation needs to build a perfect GIS traffic network model, which has a large workload.

Note: API personal key has a limit on query quota, and enterprise key quota is high. If there is a large number of query requirements, enterprise key can be provided through private mail.
If you need accessibility analysis, you can also help by private letter!

reference:
[1]Evaluation method for public transport accessibility of large public service facilities
[2] Baidu API documentation: http://lbsyun.baidu.com/index.php?title=webapi/direction-api-v2

Posted by timmy2 on Sun, 07 Nov 2021 15:21:00 -0800