天天看點

vue 接入web版本百度地圖

vue接入web版本百度地圖,之前一直有問題存在,無法進行二次搜尋,二次路線規劃,剛剛看到一位仁兄的部落格受到啟發,修改完成後功能正常了。以下為自己的源碼:

<template>
  <div class="map-container">
    <div id="allmap" class="map-container"></div>
    <div class="search-container">
      <div class="menu-content">
        <DropdownMenu>
          <DropdownItem v-model="dropDown" :options="options" />
        </DropdownMenu>
      </div>
      <div class="search-content">
        <span class="search-text" @click="changePlace">{{searchText}}</span>
        <input class="search-input" :placeholder="searchPlaceHolder" v-model="searchPlace"/>
      </div>
      <div class="query-content">
        <p class="query-btn" @click="checkQuery">查詢</p>
      </div>
    </div>
  </div>
</template>
<script>
var map
import { DropdownMenu, DropdownItem } from 'vant'
export default {
  components: {
    DropdownMenu,
    DropdownItem
  },
  data () {
    return {
      dropDown: 'BMAP_DRIVING_POLICY_LEAST_TIME',
      options: [
        { text: '最少時間', value: 'BMAP_DRIVING_POLICY_LEAST_TIME'},
        { text: '最短距離', value: 'BMAP_DRIVING_POLICY_LEAST_DISTANCE'},
        { text: '避開高速', value: 'BMAP_DRIVING_POLICY_AVOID_HIGHWAYS' }
      ],
      searchText: '起點',
      searchPlaceHolder: '請輸入起點',
      startOrEnd: true,
      searchPlace: '',
      start: '',
      end: '武漢天河國際機場'
    }
  },
  watch: {
    searchPlace (value) {
      if (this.startOrEnd) {
        this.start = value
        this.end = '武漢天河國際機場'
      } else {
        this.start = '武漢天河國際機場'
        this.end = value
      }
    }
  },
  methods: {
    //擷取位置資訊
    //BMAP_STATUS_SUCCESS	檢索成功。對應數值“0”。
    //BMAP_STATUS_CITY_LIST	城市清單。對應數值“1”。
    //BMAP_STATUS_UNKNOWN_LOCATION	位置結果未知。對應數值“2”。
    //BMAP_STATUS_UNKNOWN_ROUTE	導航結果未知。對應數值“3”。
    //BMAP_STATUS_INVALID_KEY	非法密鑰。對應數值“4”。
    //BMAP_STATUS_INVALID_REQUEST	非法請求。對應數值“5”。
    //BMAP_STATUS_PERMISSION_DENIED	沒有權限。對應數值“6”。(自 1.1 新增)
    //BMAP_STATUS_SERVICE_UNAVAILABLE	服務不可用。對應數值“7”。(自 1.1 新增)
    //BMAP_STATUS_TIMEOUT	逾時。對應數值“8”。(自 1.1 新增)
    getMyPosition () {
      // 浏覽器定位并更新位置資訊
      var point = new BMap.Point(114.2250245, 30.77836806)
      map.centerAndZoom(point, 14)
      var geolocation = new BMap.Geolocation()
      geolocation.getCurrentPosition(function(r){
        if(this.getStatus() == BMAP_STATUS_SUCCESS){
          var mk = new BMap.Marker(r.point)
          map.addOverlay(mk);
          map.panTo(r.point);
          console.log('您的位置:'+r.point.lng+','+r.point.lat)
        } else {
          console.log('failed'+this.getStatus())
        }        
      },{enableHighAccuracy: true})
    },
    getRoutePlan () {
      map.clearOverlays()
      var driving = new BMap.DrivingRoute(map, {renderOptions:{map: map, autoViewport: true}, policy: this.dropDown});
			driving.search(this.start, this.end);
    },
    changePlace () {
      this.startOrEnd = !this.startOrEnd
      this.searchPlace = ''
      if (this.startOrEnd) {
        this.searchText = '起點'
        this.searchPlaceHolder = '請輸入起點'
        this.start = ''
        this.end = '武漢天河國際機場'
      } else {
        this.searchText = '終點'
        this.searchPlaceHolder = '請輸入終點'
        this.start = '武漢天河國際機場'
        this.end = ''
      }
    },
    checkQuery () {
      if ( this.searchPlace === '') {
        this.$toast('請輸入搜尋内容!')
      } else if (this.start === '') {
        this.$toast('請輸入起點再進行搜尋!')
      } else if (this.end === '') {
        this.$toast('請輸入終點再進行搜尋!')
      } else {
        this.getRoutePlan()
      }
    }
  },
  mounted () {
    map = new BMap.Map("allmap")
    this.getMyPosition()
  }
}
</script>
<style  scoped>
.test {
  border: 1px solid lightgreen;
}
.map-container {
  width: 100%;
  height: 100%;
}
.search-container {
  z-index: 99;
  width: 90%;
  height: 2rem;
  position: absolute;
  left: 5%;
  top: 0.5rem;
  display: flex;
  flex-direction: row;
  border-radius: 18px;
  background-color: wheat;
}
/deep/ .BMap_cpyCtrl {
  display: none;
}
/deep/ .anchorBL {
  display: none;
}
/deep/ .van-dropdown-menu {
  height: 100%;
  border-radius: 18px 0px 0px 18px;
}
/deep/ .van-popup--top {
  width: 90%;
  left: 5%;
  top: 0.5rem;
}
/deep/ .van-dropdown-menu__item {
  background-color: wheat;
  border-radius: 18px 0px 0px 18px;
}
/deep/ .van-dropdown-menu__title {
  color: white;
}
.menu-content {
  width: 7rem;
}
.query-content {
  flex-grow:1;
  display:flex;
  flex-direction:column;
  justify-content:center;
}
.query-btn {
  width: 100%;
  text-align: center;
  font-size: 12px;
  color: white;
  margin-right: 3rem;
}
.search-content {
  flex-grow:1;
  display: flex;
  flex-direction: row;
  justify-content: center;
  color: white;
}
.search-text {
  width: 2rem;
  text-align: center;
  margin: auto 0px;
  font-size:12px;
  margin-right:20px;
}
.search-input {
  font-size: 12px;
  text-align: center;
  width: 6rem;
  background-color: wheat;
  outline-style: none ;
	outline-width: 0px ;
	border: none ;
	border-style: none ;
  text-shadow: none ;
}
</style>
           

注意:關鍵看map的聲明方式,使map長期保持有效,不能使用vue data的方式對map進行聲明,具體原因不詳,雖然都是對象

此處為那位仁兄的代碼:

<template>
  <div style="width: 100%;height: 100%">
    <input type="text" placeholder="出發地" style="width: 10em" id="startAddress">
    <input type="text" placeholder="目的地" style="width: 10em" id="endAddress">
    <input type='button' value='開始' @click='searchByStationName1()'/>
    <p></p>
    <div style="width:1020px;height:500px;border:1px solid gray;margin-left: 25%" id="container"></div>
    <p></p>
  </div>
</template>

<script>
var map
export default {
  name: 'search',
  data: function () {
    return {
      from: null,
      to: null
    }
  },
  mounted () {
    /* eslint-disable */
    var _this = this;
    map = new BMap.Map('container')
    map.centerAndZoom(new BMap.Point(112.89996, 28.198), 13)
    map.enableScrollWheelZoom(true) // 開啟滑鼠滾輪縮放
    map.addControl(new BMap.NavigationControl()) // 添加平移縮放控件
    map.addControl(new BMap.ScaleControl()) // 添加比例尺控件
    map.addControl(new BMap.OverviewMapControl()) // 添加縮略地圖控件

    var localSearch = new BMap.LocalSearch(map);
    localSearch.enableAutoViewport(); //允許自動調節窗體大小
  },
  methods: {//定義方法
    searchByStationName1: function () {
      var _this = this;
      var startAddrr = document.getElementById("startAddress").value;//獲得起點地名
      var localSearch = new BMap.LocalSearch(map);
      localSearch.setSearchCompleteCallback(function (searchResult) {
        var poi = searchResult.getPoi(0);//獲得起點經緯度坐标
        if (poi != null) { //判斷地名是否存在
          console.log('from poi', poi);
          _this.from = poi.point;
          console.log('from', _this.from);
          _this.searchByStationName2();
        }
        else{
          alert("請輸入正确的地名!")
        }
      });
      localSearch.search(startAddrr);
    },
    searchByStationName2: function () {
      var _this = this;
      var endAddrr = document.getElementById("endAddress").value; //獲得目的地地名
      var localSearch = new BMap.LocalSearch(map);
      localSearch.setSearchCompleteCallback(function (searchResult) {
        var poi = searchResult.getPoi(0); //獲得目的地經緯度坐标
        if (poi != null) { //判斷目的地是否存在
          _this.to = poi.point;
          _this.run();
        }
        else{
          alert("請輸入正确的地名!")
        }

      });
      localSearch.search(endAddrr);
    },
    run: function () {
      map.clearOverlays() // 清除地圖上所有的覆寫物
      var walking = new BMap.WalkingRoute(map) // 建立步行執行個體
      walking.search(this.from, this.to) // 第一個步行搜尋
      let that = this;
      walking.setSearchCompleteCallback(function () {
        console.log('completeCallback start!');
        var pts = walking.getResults().getPlan(0).getRoute(0).getPath() // 通過步行執行個體,獲得一系列點的數組

        var polyline = new BMap.Polyline(pts)
        map.addOverlay(polyline)
        console.log('pollyline!', polyline);
        var m1 = new BMap.Marker(that.from) // 建立2個marker
        var m2 = new BMap.Marker(that.to)
        map.addOverlay(m1)
        map.addOverlay(m2)

        var lab1 = new BMap.Label('起點', {position: that.from}) // 建立2個label
        var lab2 = new BMap.Label('終點', {position: that.to})
        map.addOverlay(lab1)
        map.addOverlay(lab2)
        console.log('setTimeout!');
        setTimeout(function () {
          map.setViewport([that.from, that.to]) // 調整到最佳視野
        }, 1000)
      })
    }
  }
}

</script>

<style scoped>


</style>
           

那位仁兄的部落格位址也貼上,表示感謝:https://blog.csdn.net/weixin_43693592/article/details/86692264