高德地圖支持公交線程查詢功能。線上示例;
線上示例說明
接口返回的數據結構:

path和via_stops字段詳情:
...
path: [
{
Q: 39.97741, R: 116.39788099999998, lng: 116.397881, lat: 39.97741
},
...
],
via_stops: [
{
id: "BV10424760",
location: {
Q: 39.97741,
R: 116.39788099999998,
lat: 39.97741,
lng: 116.397881
},
name: "北土城公交場站",
sequence: 1
},
...
]
...
流程:
-
實例化Map組件
-
獲取要查詢的公交線路
-
檢查是否存在LineSearch的實例,不存在則創建一個。在實例化時需要的參數如下:
linesearch = new AMap.LineSearch({ pageIndex: 1, city: '北京', pageSize: 1, extensions: 'all' }); -
調用LineSearch實例的search方法,第一個參數為公交站點名稱,第二個參數是請求成功的回調。
-
執行上一步的回調,第一個參數是接口返回的數據。數據的結構在上面已經貼出來了。
接入說明
- 與示例相同通過
script標簽直接引入,參考示例代碼操作。 - 通過react-amap接入react項目。
下面詳細說明第二種接入方式。
ps:當前接入的react-amap版本為v1.2.7
按照github項目中接入高德地圖插件的文檔說明,發現無法成功添加LineSearch組件。仔細查看源碼發現當前版本僅支持了一下幾個插件。
//node_modules/react-amap/lib/map/index.js
function installPlugin(name, opts) {
opts = opts || {};
switch (name) {
case 'Scale':
case 'ToolBar':
case 'OverView':
case 'MapType':
this.setMapPlugin(name, opts);
break;
case 'ControlBar':
this.setControlBar(opts);
break;
default:
// do nothing
}
}
因此需要采用其他形式引入該插件。示例代碼如下:
import { Map, Marker } from 'react-amap';
...
constructor() {
this.mapPlugins = [];
this.state = {
position: {//121.624604,29.85988
longitude: '121.624604',
latitude: '29.85988'
}
};
this.lineSearchOpts = {
pageIndex: 1,
city: '寧波',
pageSize: 1,
extensions: 'all'
};
let that = this;
this.mapEvents = {
created(m){
console.log('這里的 m 就是創建好的高德地圖實例')
console.log(m)
m.plugin(['AMap.LineSearch'], () => {
//公交線路查詢插件
const defaultSearchName = '515路';
if(!linesearch){
linesearch = new AMap.LineSearch(that.lineSearchOpts);
}
that.lineSearch(defaultSearchName);
});
}
};
}
lineSearch = (busLineName) => {
let that = this;
linesearch.search(busLineName, function(status, result) {
map.clearMap()
if (status === 'complete' && result.info === 'OK') {
that.dealWithBusPathResult(result);
} else {
alert(result);
}
});
}
dealWithBusPathResult = (data) => {
console.log('查詢到的公交線路數據為', data);
}
...
render() {
return (
<div>
<MAp
amapkey=""
plugins={this.mapPlugins}
center={this.state.position}
events={this.mapEvents}
zoom={15}
>
//這里根據需要放各個公交站點的maker、始發站maker、終點站maker
</Map>
</div>
)
}
...
