## Python - Analysis of reachable circle of multiple traffic modes

DataCharm 2021-02-22 23:08:55
python analysis reachable circle multiple

Lei always sent me this picture the other day , I can't help recalling the little things of my life in school , I really want to go back to Chengdu , I believe you are all like me ！

This time, we will use python Call Baidu api Realization Construction of accessibility circle for different modes of transportation , My high school classmate village head asked me to help him use Baidu a few days ago api Climb up poi data , I did some research , Found this api It's good to use , Except for climbing poi It can also achieve path planning , Just write a little bit of code to play , Now share with you .

First of all, a brief introduction to Baidu api The function of path planning , We can enter the mode of transportation 、 The starting point 、 The latitude and longitude coordinates of the destination , Baidu will return to us a json file , It contains automatically planned paths 、 The total length of the path and the estimated travel time . therefore , We can analyze the reachable circle of various modes of transportation at a point , Simply put, it's starting at that point 、 In some form of travel 、 The range that can be reached at a certain time . Besides , If you can also know the number of jobs in each community , Then we can calculate the accessibility 了 , Of course , This is beyond the scope of this article .

What we want to do this time is to analyze the cycling circle of Tianfu Square , Here's the code .

First, switch , It's just the same , See my first article for details ：

```import pandas as pd
import numpy as np
import geopandas as gpd
import matplotlib.pyplot as plt
from shapely.geometry import Point
from fiona.crs import from_epsg
plt.rcParams['font.sans-serif']=['Arial Unicode MS']
plt.rcParams['axes.unicode_minus']=False
pd.set_option('display.max_columns', None)```

And then draw a grid , I won't write the code here , I wrote about it in the article about car Hailing , You can go to the last article to see , The direct result .

The specific areas to be analyzed are shown in the figure above , It's probably within the Third Ring Road of Chengdu , It's painted 40*40 The grid of , What we need to calculate is the riding time from Tianfu Square to each grid center . How to create a central point in the network about the car that article can also be found , It is omitted here .

Next we're going to call api It's time to calculate . First import the crawler and parse json Files need packages ：

```import requests
import json```

Then start calling api Calculation ：

```area['ride_time'] = 0 ### area It's the grid of creation
for i in range(len(area)):
ak = #### Yours ak
url = 'http://api.map.baidu.com/directionlite/v1/riding?origin=30.66012,104.06352&coord_type=wgs84&destination={},{}&ak={}'.format(area_point.iloc[i,0].y,area_point.iloc[i,0].x,ak)
data = requests.get(url).json()
if data['status'] == 0:
area.loc[i,'ride_time'] = data['result']['routes'][0]['duration']
else:
area.loc[i,'ride_time'] = 0```

Here's an explanation , First of all, register as the developer of Baidu map , So you get a api key, abbreviation ak, With this ak You can call Baidu's api 了 . But Baidu's path planning api If you go whoring for nothing, you can call at most 2000 Time , Local tyrants can be members , If you are not a local tyrant, you can register a few more numbers

.

This is a api Parameters that need to be entered , You can find , There are a lot of options , except ak, The latitude and longitude of the starting point and the ending point must be input , You can also choose an ordinary bicycle or a small electric donkey , Very intimate .

After the input parameter is called api, Will return a json file , Specific content Baidu's development documents also have an explanation ：

You can see , The first is the status code , And then there's all kinds of information , What we need is actually result Below duration, That's the line time , For returned json And then analyze it according to key Just extract it . The specific code is all on it .

But there's a problem that needs attention , Some routes return status codes that are not 0, Erroneous . My approach to this point is if something goes wrong , Just set the time consumption of this line to 0, And then do a simple interpolation ：

```for i in range(len(area1)):
if area1.iloc[i,1] == 0:
area1.iloc[i,1] = (area1.iloc[i-1,1]+area1.iloc[i+1,1])/2```

Of course, this is only a very rough method , If you write a paper, you'll still be obedient arcgis Interpolation in space .

Above, we get the riding time from Tianfu Square to each grid , Now let's visualize ;

`area1['ride_time'] = -area1['ride_time']`

Here, I'll first take the opposite number of time spent , because python I can't find the lighter the color the higher the number is

, If you take the opposite number, the shorter the travel time is, the larger the value will be , The darker the color of the visualization , It's convenient for us to observe .

```import contextily as ctx
chengdu = chengdu.to_crs(from_epsg(3857))
area1 = area1.to_crs(from_epsg(3857)) ## Project into web Mercator coordinates
base = area1.plot(column='ride_time',figsize=(10,10),cmap='Blues',scheme='fisher_jenks',k=7,alpha=0.55)
plt.xlim(11579000,11590000)
plt.ylim(3583500,3595000)
plt.gca().xaxis.set_major_locator(plt.NullLocator()) # Get rid of x Axis scale
plt.gca().yaxis.set_major_locator(plt.NullLocator()) # last year y Axis scale
plt.title(' Tianfu Square can reach the circle by bike ',fontsize=20)
plt.savefig(' Tianfu Square can reach the circle by bike .jpg',dpi=300)```

And that's the end result , The depth of the color represents the time spent riding from Tianfu Square , It's distributed in circles , Generally speaking, it is more realistic （ Of course , The grid size is too large, which makes it look a little ugly , You can draw more squares or divide them with hexagons , It looks more advanced ）.

Next, let's take a look at starting from Tianfu Square 15 It's a 15 minute bike ride ：

`area2 = area1[area1['ride_time']>-900] ## Screening travel time less than 900s Lattice of `
```base = area2.plot(color='Red',alpha=0.4,figsize=(10,10))
plt.title(' Riding in Tianfu Square 15 It's a lap in a minute ',fontsize=20)
plt.gca().xaxis.set_major_locator(plt.NullLocator()) # Get rid of x Axis scale
plt.gca().yaxis.set_major_locator(plt.NullLocator()) # last year y Axis scale
plt.savefig(' Riding in Tianfu Square 15 It's a lap in a minute .jpg',dpi=300)```

Quack , It can be seen that , If you ride hard , From Tianfu Square 15 Minutes can still kick a ring

.

Besides , Baidu also provides driving 、 transit 、 Walking and other modes of transportation Path planning of api, You can try it yourself , Because of my ak Reached the daily limit , I won't show you , You can refer to Baidu map api Try it yourself , Use the code above to put url Just change it .

This is the end of this article ！Yuan It's the end of the three chapters , Thank you for your encouragement and support . The purpose of writing this official account is to share with you and make progress together , I think the most important thing about learning in the Internet age is the spirit of sharing , In fact, our bags are shared and maintained by all kinds of gods , Every time I think about this, I am deeply moved . therefore , If my article helps you , Please like it more and forward it more , Let more people see , This is also an encouragement to me , thank you