基於高德地圖實現的公交線路查詢功能

高德地圖支持公交線程查詢功能。線上示例;javascript

線上示例說明

接口返回的數據結構:java

公交線路查詢接口返回的數據結構

path和via_stops字段詳情:node

...
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
    },
    ...
]
...

流程:react

  1. 實例化Map組件git

  2. 獲取要查詢的公交線路github

  3. 檢查是否存在LineSearch的實例,不存在則建立一個。在實例化時須要的參數以下:api

    linesearch = new AMap.LineSearch({
        pageIndex: 1,
        city: '北京',
        pageSize: 1,
        extensions: 'all'
    });
  4. 調用LineSearch實例的search方法,第一個參數爲公交站點名稱,第二個參數是請求成功的回調。數據結構

  5. 執行上一步的回調,第一個參數是接口返回的數據。數據的結構在上面已經貼出來了。this

接入說明

  1. 與示例相同經過script標籤直接引入,參考示例代碼操做。
  2. 經過react-amap接入react項目。

下面詳細說明第二種接入方式。spa

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>
    )
}
...

jsfiddle在線代碼示例

相關文章
相關標籤/搜索