【重點突破】—— 百度地圖在React單頁面應用中的使用

前言:百度地圖是網頁中使用地圖的經常使用第三方工具,這裏結合React項目中學到的應用場景總結一些使用要點。javascript


1、在網頁中嵌入百度地圖php

  1. 控制檯:查看應用、建立應用(得到百度地圖密鑰)
  2. 開發文檔:選擇JavaScriptAPI

    Referer白名單:*   (例如*.tedu.cn  域名只能有這個字段,才能使用這個密鑰,避免因盜用密鑰使用本身網站的服務)html

  • 建立一個網站:登陸百度地圖開發者平臺,爲網站申請一個地圖的AccesKey(全球惟一網站密鑰)java

  • 在本身的網頁中嵌入百度地圖提供的API,嵌入百度地圖
  1. 引入一個特殊的script,關鍵放置密鑰的地方:
    <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=你的密鑰"></script>
  2. 核心代碼:react

    var map = new BMap.Map("container");  //建立地圖實例
    var point = new BMap.Point(116.300829, 39.915836); //建立點座標(天安門座標爲例)
    map.centerAndZoom(point, 17); //以指定點爲中心並縮放 (17表示層級)
  • 經常使用控件:可能會變,不用記,查文檔便可ios

  1. 啓用滾輪縮放方法:map.enableScrollWheelZoom(true);ajax

  2. 添加導航控件:map.addControl(new BMap.NacigationControl());axios

  3. 添加縮放控件:map.addControl(new BMap.ScalControl());api

  4. 添加概覽圖控件:map.addControl(new BMap.OverviewMapControl()); antd

  5. 添加地圖類型控件:map.addControl(new BMap.MapTypeControl()); 

  • 經常使用覆蓋物:小標記/小說明/小頁籤

    var mk = new BMap.Marker(point);
    map.addOverlay(mk);
    marker.setAnimation(BMap)ANIMATION_BOUNCE); //彈跳動畫

      

2、繪製訂單地圖

  • Easy Mock訂單詳情數據接口:/order/detail
    {
      "code": 0,
      "msg": "",
      "list": {
        "status": 2,
        "order_sn": "T1803244422704080JGJI",
        "bike_sn": '802410001',
        "mode|1-2": 1,
        "start_location": "北京市昌平區回龍觀東大街",
        "end_location": "北京市海淀區奧林匹克公園",
        "city_id": 1,
        "mobile": "13597482075",
        "user_name": "@cname",
        "distance": 10000,
        "bike_gps": "116.398806,40.008637",
        "start_time": 1546580667000,
        "end_time": 1546608995000,
        "total_time": 224,
        "position_list": [{
            "lon": 116.361221,
            "lat": 40.043776
          },
          {
            "lon": 116.363736,
            "lat": 40.038086
          },
          {
            "lon": 116.364599,
            "lat": 40.036484
          },
          {
            "lon": 116.373438,
            "lat": 40.03538
          },
          {
            "lon": 116.377966,
            "lat": 40.036263
          },
          {
            "lon": 116.379762,
            "lat": 40.03654
          },
          {
            "lon": 116.38084,
            "lat": 40.033225
          },
          {
            "lon": 116.38084,
            "lat": 40.029413
          },
          {
            "lon": 116.381343,
            "lat": 40.021291
          },
          {
            "lon": 116.381846,
            "lat": 40.015821
          },
          {
            "lon": 116.382637,
            "lat": 40.008084
          },
          {
            "lon": 116.398806,
            "lat": 40.008637
          }
        ],
        "area": [{
            "lon": "116.274737",
            "lat": "40.139759",
            "ts": null
          },
          {
            "lon": "116.316562",
            "lat": "40.144943",
            "ts": null
          },
          {
            "lon": "116.351631",
            "lat": "40.129498",
            "ts": null
          },
          {
            "lon": "116.390582",
            "lat": "40.082481",
            "ts": null
          },
          {
            "lon": "116.38742",
            "lat": "40.01065",
            "ts": null
          },
          {
            "lon": "116.414297",
            "lat": "40.01181",
            "ts": null
          },
          {
            "lon": "116.696242",
            "lat": "39.964035",
            "ts": null
          },
          {
            "lon": "116.494498",
            "lat": "39.851306",
            "ts": null
          },
          {
            "lon": "116.238086",
            "lat": "39.848647",
            "ts": null
          },
          {
            "lon": "116.189454",
            "lat": "39.999418",
            "ts": null
          },
          {
            "lon": "116.244646",
            "lat": "39.990574",
            "ts": null
          },
          {
            "lon": "116.281441",
            "lat": "40.008703",
            "ts": null
          },
          {
            "lon": "116.271092",
            "lat": "40.142201",
            "ts": null
          },
          {
            "lon": "116.271092",
            "lat": "40.142201",
            "ts": null
          }
        ],
        "area_list": null,
        "npl_list": [{
          "id": 8265,
          "name": "北辰世紀中心-a座",
          "city_id": 1,
          "type": 3,
          "status": 0,
          "map_point": "116.39338796444|40.008120315215;116.39494038009002|40.008177258745;116.39496911688|40.006268094213;116.39512457763|40.004256795877;116.39360214742|40.004222412241;116.39357190147|40.005075745782;116.39351397873|40.005836165232;116.39338796444|40.008120315215",
          "map_point_array": [
            "116.39338796444|40.008120315215",
            "116.396053|40.008273",
            "116.396448|40.006338",
            "116.396915|40.004266",
            "116.39192|40.004072",
            "116.391525|40.004984",
            "116.391381|40.005924",
            "116.391166|40.007913"
          ],
          "map_status": 1,
          "creator_name": "趙程程",
          "create_time": 1507863539000
        }]
      }
    }  
  • 建立ak,加載百度地圖sdk:【百度地圖開發平臺

  • 地圖初始化:public->index.html中引入百度地圖第三方JS庫

    <title>React App</title> <!--第三方庫 百度地圖--> <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=vALBxRpSKdoPxLyDcuMQPWFL8avoRTP0"></script> 

    pages->order->detail.js中:調用new window.BMap.Map('id')初始化Map

    //初始化地圖 renderMap = (list) => { this.map = new window.BMap.Map('orderDetailMap'); // this.map.centerAndZoom('北京', 11) //添加地圖控件 this.addMapControl(); //調用路線圖繪製方法 this.drawBikeRoute(list.position_list); //調用服務區繪製方法 this.drawServiceArea(list.area); } 

    注意:單頁面應用必須調用window.BMap全局變量才能識別BMap,不然會報錯no defined;多頁面應用中直接使用new BMao.Map('id')便可

  • 添加地圖控件

    //添加地圖控件 addMapControl = () => { let map = this.map; map.addControl(new window.BMap.ScaleControl({ anchor: window.BMAP_ANCHOR_TOP_RIGHT })); map.addControl(new window.BMap.NavigationControl({ anchor: window.BMAP_ANCHOR_TOP_RIGHT })); }
  • 繪製用戶行駛路線

    //繪製用戶行駛路線圖
    drawBikeRoute = (positionList) => {
            let map = this.map;
            let startPoint = '';
            let endPoint = '';
            if(positionList.length > 0){
               //起點
               let first = positionList[0]; 
               startPoint = new window.BMap.Point(first.lon, first.lat);
               let startIcon = new window.BMap.Icon('/assets/start_point.png', new window.BMap.Size(36,42),{
                   imageSize: new window.BMap.Size(36,42),
                   anchor: new window.BMap.Size(36,42)
               })
    
               let startMarker = new window.BMap.Marker(startPoint, {icon: startIcon});
               this.map.addOverlay(startMarker);
    
               //終點
               let last = positionList[positionList.length-1]; 
               endPoint = new window.BMap.Point(last.lon, last.lat);
               let endIcon = new window.BMap.Icon('/assets/end_point.png', new window.BMap.Size(36,42),{
                   imageSize: new window.BMap.Size(36,42),
                   anchor: new window.BMap.Size(36,42)
               })
               let endMarker = new window.BMap.Marker(endPoint, {icon: endIcon});
               this.map.addOverlay(endMarker);
              
               //鏈接路線圖
               let trackPoint = [];
               for(let i=0; i<positionList.length; i++){
                   let point = positionList[i]
                   trackPoint.push(new window.BMap.Point(point.lon, point.lat))
               }
    
               let polyline = new window.BMap.Polyline(trackPoint, {
                   strokeColor: '#1869AD',
                   strokeWeight: 3,
                   strokeOpacity: 1
               })
               this.map.addOverlay(polyline);
    
               //設置地圖中心點
               this.map.centerAndZoom(endPoint, 11)
            }
    }   
    
    //繪製服務區
    drawServiceArea = (positionList) => {
            let trackPoint = [];
            for(let i=0; i<positionList.length; i++){
                   let point = positionList[i]
                   trackPoint.push(new window.BMap.Point(point.lon, point.lat))
            }
    
            let polygon = new window.BMap.Polygon(trackPoint, {
                strokeColor: '#CE0000',
                strokeWeight: 4,
                strokeOpacity: 1,
                fillColor: '#ff8605',
                fillOpacity: 0.4
            }) 
            this.map.addOverlay(polygon);
    }

 

3、繪製車輛地圖

  • Easy Mock車輛地圖分佈的數據接口:/map/bike_list
    {
      "code": 0,
      "list": {
        "total_count": 100,
        "bike_list": ['116.356619,40.017782', '116.437107,39.975331', '116.34972,40.070808', '116.323849,39.964714', '116.404912,40.015129', '116.365243,39.958078'],
        "route_list": ['116.353101,40.067835', '116.357701,40.053699', '116.374086,40.027626', '116.397801,40.01641'],
        "service_list": [{
            "lon": "116.274737",
            "lat": "40.139759",
            "ts": null
          },
          {
            "lon": "116.316562",
            "lat": "40.144943",
            "ts": null
          },
          {
            "lon": "116.351631",
            "lat": "40.129498",
            "ts": null
          },
          {
            "lon": "116.390582",
            "lat": "40.082481",
            "ts": null
          },
          {
            "lon": "116.38742",
            "lat": "40.01065",
            "ts": null
          },
          {
            "lon": "116.414297",
            "lat": "40.01181",
            "ts": null
          },
          {
            "lon": "116.696242",
            "lat": "39.964035",
            "ts": null
          },
          {
            "lon": "116.494498",
            "lat": "39.851306",
            "ts": null
          },
          {
            "lon": "116.238086",
            "lat": "39.848647",
            "ts": null
          },
          {
            "lon": "116.189454",
            "lat": "39.999418",
            "ts": null
          },
          {
            "lon": "116.244646",
            "lat": "39.990574",
            "ts": null
          },
          {
            "lon": "116.281441",
            "lat": "40.008703",
            "ts": null
          },
          {
            "lon": "116.271092",
            "lat": "40.142201",
            "ts": null
          },
          {
            "lon": "116.271092",
            "lat": "40.142201",
            "ts": null
          }
        ]
      }
    }
  • pages->map->bikeMap.js中:調用new window.BMap.Map('id')初始化Map

    //初始化地圖
    renderMap = (res) => {
            //渲染地圖數據
            let list = res.list.route_list;
            this.map = new window.BMap.Map('container');
            let gps1 = list[0].split(',');
            let startPoint = new window.BMap.Point(gps1[0],gps1[1]);
            let gps2 = list[list.length-1].split(',');
            let endPoint = new window.BMap.Point(gps2[0],gps2[1]);
            this.map.centerAndZoom(endPoint, 11);
            
            //起點 -- 圖標Icon/覆蓋物Marker/添加addOverlay
            let startPointIcon = new window.BMap.Icon('/assets/start_point.png', new window.BMap.Size(36,42),{
                imageSize: new window.BMap.Size(36,42),
                anchor: new window.BMap.Size(18,42) //偏移
            })
            let bikeMarkerStart = new window.BMap.Marker(startPoint,{icon: startPointIcon})
            this.map.addOverlay(bikeMarkerStart)
    
            //終點
            let endPointIcon = new window.BMap.Icon('/assets/end_point.png', new window.BMap.Size(36,42),{
                imageSize: new window.BMap.Size(36,42),
                anchor: new window.BMap.Size(18,42)
            })
            let bikeMarkerEnd = new window.BMap.Marker(endPoint,{icon: endPointIcon})
            this.map.addOverlay(bikeMarkerEnd)
    
            //繪製車輛行駛路線
            let routeList = [];
            list.forEach((item) => {
                let p = item.split(',');
                routeList.push(new window.BMap.Point(p[0],p[1]));
            })
            let polyLine = new window.BMap.Polyline(routeList, {
                strokeColor: '#ef4136',
                strokeWeight: 2,
                strokeOpacity: 1
            })
            this.map.addOverlay(polyLine);
    
            //繪製服務區
            let servicePointList = [];
            let serviceList = res.list.service_list;
            serviceList.forEach((item) => {
                servicePointList.push(new window.BMap.Point(item.lon, item.lat));
            })
            let polyServiceLine = new window.BMap.Polyline(servicePointList, {
                strokeColor: '#1869AD',
                strokeWeight: 3,
                strokeOpacity: 1
            })
            this.map.addOverlay(polyServiceLine);
    
            //添加地圖中的自行車圖標
            let bikeList = res.list.bike_list;
            let bikeIcon = new window.BMap.Icon('/assets/bike.jpg', new window.BMap.Size(36,42),{
                imageSize: new window.BMap.Size(36,42),
                anchor: new window.BMap.Size(18,42)
            })
            bikeList.forEach((item) => {
                let p = item.split(',');
                let point = new window.BMap.Point(p[0],p[1]);
                let bikeMarker = new window.BMap.Marker(point, {icon: bikeIcon})
                this.map.addOverlay(bikeMarker);
            })
           
            //添加地圖控件
            this.map.addControl(new window.BMap.ScaleControl({ anchor: window.BMAP_ANCHOR_TOP_RIGHT }));
            this.map.addControl(new window.BMap.NavigationControl({ anchor: window.BMAP_ANCHOR_TOP_RIGHT }));
     }
  • 實例代碼:

    import React from 'react'
    import {Card, Form} from 'antd'
    import axios from './../../axios'
    import BaseForm from '../../components/BaseForm'
    
    export default class BikeMap extends React.Component{
    
        state = {
            list:[]
        }
    
        map='';
    
        params = {
            page: 1
        }
    
        formList = [
            {
                type: 'SELECT',
                label: '城市',
                field: 'city_id',
                placeholder: '所有',
                initialValue: '0',
                list: [
                    {id: '0', name: '所有'},
                    {id: '1', name: '北京'},
                    {id: '2', name: '天津'},
                    {id: '3', name: '深圳'},
                ]
                
            },{
                type: '時間查詢'
            },{
                type: 'SELECT',
                label: '訂單狀態',
                field: 'order_status',
                placeholder: '所有',
                initialValue: '0',
                list: [
                    {id: '0', name: '所有'},
                    {id: '1', name: '進行中'},
                    {id: '2', name: '行程結束'}
                ]
            }
        ]
    
        componentDidMount(){
            this.requestList();
        }
    
        requestList = () => {
           axios.ajax({
               url: '/map/bike_list',
               data: {
                   params: this.params
               }
           }).then((res) => {
               if(res.code === 0){
                   this.setState({
                       total_count: res.list.total_count
                   })
                   this.renderMap(res);
               }
           })
        }
    
        //查詢表單
        handleFilterSubmit = (filterParams) => {
            this.params = filterParams;
            this.requestList();
        }
    
        //初始化地圖
        renderMap = (res) => {
            //渲染地圖數據
            let list = res.list.route_list;
            this.map = new window.BMap.Map('container');
            let gps1 = list[0].split(',');
            let startPoint = new window.BMap.Point(gps1[0],gps1[1]);
            let gps2 = list[list.length-1].split(',');
            let endPoint = new window.BMap.Point(gps2[0],gps2[1]);
            this.map.centerAndZoom(endPoint, 11);
            
            //起點 -- 圖標Icon/覆蓋物Marker/添加addOverlay
            let startPointIcon = new window.BMap.Icon('/assets/start_point.png', new window.BMap.Size(36,42),{
                imageSize: new window.BMap.Size(36,42),
                anchor: new window.BMap.Size(18,42) //偏移
            })
            let bikeMarkerStart = new window.BMap.Marker(startPoint,{icon: startPointIcon})
            this.map.addOverlay(bikeMarkerStart)
    
            //終點
            let endPointIcon = new window.BMap.Icon('/assets/end_point.png', new window.BMap.Size(36,42),{
                imageSize: new window.BMap.Size(36,42),
                anchor: new window.BMap.Size(18,42)
            })
            let bikeMarkerEnd = new window.BMap.Marker(endPoint,{icon: endPointIcon})
            this.map.addOverlay(bikeMarkerEnd)
    
            //繪製車輛行駛路線
            let routeList = [];
            list.forEach((item) => {
                let p = item.split(',');
                routeList.push(new window.BMap.Point(p[0],p[1]));
            })
            let polyLine = new window.BMap.Polyline(routeList, {
                strokeColor: '#ef4136',
                strokeWeight: 2,
                strokeOpacity: 1
            })
            this.map.addOverlay(polyLine);
    
            //繪製服務區
            let servicePointList = [];
            let serviceList = res.list.service_list;
            serviceList.forEach((item) => {
                servicePointList.push(new window.BMap.Point(item.lon, item.lat));
            })
            let polyServiceLine = new window.BMap.Polyline(servicePointList, {
                strokeColor: '#1869AD',
                strokeWeight: 3,
                strokeOpacity: 1
            })
            this.map.addOverlay(polyServiceLine);
    
            //添加地圖中的自行車圖標
            let bikeList = res.list.bike_list;
            let bikeIcon = new window.BMap.Icon('/assets/bike.jpg', new window.BMap.Size(36,42),{
                imageSize: new window.BMap.Size(36,42),
                anchor: new window.BMap.Size(18,42)
            })
            bikeList.forEach((item) => {
                let p = item.split(',');
                let point = new window.BMap.Point(p[0],p[1]);
                let bikeMarker = new window.BMap.Marker(point, {icon: bikeIcon})
                this.map.addOverlay(bikeMarker);
            })
           
            //添加地圖控件
            this.map.addControl(new window.BMap.ScaleControl({ anchor: window.BMAP_ANCHOR_TOP_RIGHT }));
            this.map.addControl(new window.BMap.NavigationControl({ anchor: window.BMAP_ANCHOR_TOP_RIGHT }));
        }
        
        render(){
            return (
                <div>
                    <Card>
                        <BaseForm formList={this.formList} filterSubmit={this.handleFilterSubmit} />
                    </Card>
                    <Card style={{marginTop: 10}}>
                        <div>共{this.state.total_count}輛車</div>
                        <div id="container" style={{height: 500}}></div>
                    </Card>
                </div>
            )
        }
    }

注:轉載請註明出處  

相關文章
相關標籤/搜索