基于高德地图实现的公交线路查询功能

高德地图支持公交线程查询功能。线上示例;

线上示例说明

接口返回的数据结构:

公交线路查询接口返回的数据结构

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

流程:

  1. 实例化Map组件
  2. 获取要查询的公交线路
  3. 检查是否存在LineSearch的实例,不存在则创建一个。在实例化时需要的参数如下:

     linesearch = new AMap.LineSearch({
        pageIndex: 1,
        city: '北京',
        pageSize: 1,
        extensions: 'all'
    });
  4. 调用LineSearch实例的search方法,第一个参数为公交站点名称,第二个参数是请求成功的回调。
  5. 执行上一步的回调,第一个参数是接口返回的数据。数据的结构在上面已经贴出来了。

接入说明

  1. 与示例相同通过script标签直接引入,参考示例代码操作。
  2. 通过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>
    )
}
...

jsfiddle在线代码示例

猜你喜欢

转载自www.cnblogs.com/foxNike/p/10288023.html
今日推荐