VUE百度地图API调用(手机端、PC端、微信通用)

百度地图API-示例中心:

https://lbsyun.baidu.com/jsdemo.htm#aCreateMap

1.引入百度地图(此处用到的是V2.0版本)

  1> 建立一个js文件,例 map.js

export function loadBMap(funcName) {
    var script = document.createElement("script");
    script.src = "http://api.map.baidu.com/api?v=2.0&ak=你申请的AK&callback=" + funcName;
    document.body.appendChild(script);
}

  2> 在需要使用百度地图的页面调用 map.js

import {loadBMap} from '@/utils/map'

2.引入完成后,进行百度地图初始化

  1> 创建一个地图“容器”

<div id="map-container"></div>

  2> 初始化一个简单的百度地图

const that = this
let lng = 116.404
let lat = 39.928
/* 百度地图 */
window.initBaiduMapScript = () =>{
  that.map = new BMap.Map('map-container');
  that.map.centerAndZoom(new BMap.Point(lng, lat), 15);

  //开启鼠标滚轮缩放
  that.map.enableScrollWheelZoom(true);

  // 添加比例尺控件
  var scaleCtrl = new BMap.ScaleControl();
  that.map.addControl(scaleCtrl);

  // 添加比例尺控件
  var zoomCtrl = new BMap.NavigationControl();
  that.map.addControl(zoomCtrl);  
 // 监听地图加载完成后-关闭加载层
that.map.addEventListener('tilesloaded', function () {

});

}
loadBMap('initBaiduMapScript');

效果图

VUE百度地图API调用(手机端、PC端、微信通用)

至此,一个简单的地图就加载完成了。

接下来进行一些扩展

1. 百度地图输入地址搜索并定位到当前搜索位置

<input id="suggestId" type="text" v-model="searchVal" placeholder="请输入地址">
<button @click="search()">搜索</button>
// 建立一个自动完成的对象
var ac = new BMap.Autocomplete({
  "input" : "suggestId",
  "location" : that.map
});
// 搜索-点击下拉列表后的事件
ac.addEventListener("onconfirm", function(e) {
  var _value = e.item.value;
  that.searchVal = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
  // 搜索
  that.search();
});
// 搜索-地图
search(){
  const that = this
  //智能搜索
  var local = new BMap.LocalSearch(that.map, {
    onSearchComplete: ()=>{
      //获取第一个智能搜索的结果
      const pp = local.getResults().getPoi(0).point;
      that.map.centerAndZoom(pp, 18);
    }
  });
  local.search(that.searchVal);
},

 效果图

VUE百度地图API调用(手机端、PC端、微信通用)

2. 在地图上添加、删除Marker标记(覆盖物)

// 添加地图标记
addMarkFn(lng, lat){
  const that = this
  const localInfo = {
    lng,
    lat
  }
  // 创建标记图标
  // const myIcon = new BMap.Icon(this.markerImg, new BMap.Size(19, 24));
  // 创建点标记
  const point = new BMap.Point(lng, lat);
  // 创建Marker标注
  const marker = new BMap.Marker(point, {
    // enableDragging: true,
    // icon: myIcon
  });

  // 用所定位的经纬度查找所在地省市街道等信息
  const getLocationInfo = () => new Promise((resolve, reject)=>{ // 设置aa函数返回promise对象
    var gc = new BMap.Geocoder();
    gc.getLocation(point, function (rs) {
      if (rs.surroundingPois.length > 0) {
        localInfo.address =  rs.address+rs.surroundingPois[0].title;
      } else {
        localInfo.address = rs.address;
      }
      console.log(localInfo);//地址信息
      resolve(localInfo)
    });
  })
  getLocationInfo().then(res=>{
    var opts = {
      width : 100,     // 信息窗口宽度
      height: 100,     // 信息窗口高度
      title : '信息窗口标题-故宫博物馆' // 信息窗口标题
    }
    const tipHtml =
      "<p class='m0 font-12'>地址:"+localInfo.address+"</p>"+
      "<a href='http://api.map.baidu.com/marker?location="+lat+","+lng+"&title="+localInfo.address+"&content=内容介绍&mode=driving&output=html'>导航去这里</a>"+
      "<p class='m0 mt3 font-12'>" +
      "<span class='marker-del' onclick=delMarkFn('"+lng+"','"+lat+"')>删除</span>" +
      "</p>"
    // 创建信息窗口对象
    var infoWindow = new BMap.InfoWindow(tipHtml, opts);
    marker.addEventListener("click", function(){
      //开启信息窗口
      this.map.openInfoWindow(infoWindow, point);
      // 阻止冒泡
      window.event? window.event.cancelBubble = true : e.stopPropagation();
    });
  })
  // 在地图上添加点标记
  this.map.addOverlay(marker);
  // 设置标注
  var label = new BMap.Label("<span>故宫博物馆</span>",{offset:new BMap.Size(20,-10)});
  marker.setLabel(label);
},

// 删除地图标记
delMarkFn(lng, lat){
  var point = new BMap.Point(lng, lat);
  var allOverlay = this.map.getOverlays();
  for(var j = 0;j<allOverlay.length;j++) {
    //删除指定经度的点
    if (allOverlay[j].toString()=="[object Marker]" && allOverlay[j].getPosition().lng == lng && allOverlay[j].getPosition().lat == lat ) {
      this.map.removeOverlay(allOverlay[j]);
    }
  }
  this.map.closeInfoWindow(point)
},

备注(常用):

// 清除地图上所有覆盖物
that.map.clearOverlays();
// 在地图上绘制圆范围
var circle = new BMap.Circle(point, 20, {
  strokeColor: 'red',
  strokeWeight: 1,
  strokeOpacity: 0.2
});
this.map.addOverlay(circle);

效果图

VUE百度地图API调用(手机端、PC端、微信通用)

3.监听百度地图点击事件

// 点击地图添加标记
that.map.addEventListener('click', function (e) {
  console.log('点击了地图,点击位置经纬度为:' + e.point.lng + ',' + e.point.lat);
  // 点击后需要触发的事件,例-点击添加marker
 that.addMarkFn(e.point.lng, e.point.lat)
});

效果图

VUE百度地图API调用(手机端、PC端、微信通用)

4. 使用微信浏览器打开带有百度地图的页面

用微信浏览器打开含有百度地图的页面时,无法通过 new BMap.Geolocation() 定位到当前位置,这时需要调用微信SDK才可获取当前位置坐标

 a> 安装微信sdk

npm i weixin-js-sdk --save-dev

 b> 初始化微信sdk,创建一个wx.js

  wx.js

//微信sdk依赖
import wx from 'weixin-js-sdk'
//要用到微信API
import {getWXSignature} from '@/api/api'

function getJSSDK(url, dataForWeixin) {
  return new Promise((resolve, reject) => {
    getWXSignature({url: url}).then(res => {
      wx.config({
        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
        //下面这里不用管  让后台看一下  让他返给你
        appId: res.data.appId, // 必填,公众号的唯一标识
        timestamp: res.data.timestamp, // 必填,生成签名的时间戳
        nonceStr: res.data.nonceStr, // 必填,生成签名的随机串
        signature: res.data.signature, // 必填,签名
        jsApiList: [
          'updateAppMessageShareData',
          'updateTimelineShareData',
          "getLocation",
        ] // 必填,需要使用的JS接口列表
      })

      wx.error((err)=>{
        console.log(err,555666)
      })
      resolve()
    }).catch(()=>{
      reject()
    })
  })
}

export default {
  // 获取JSSDK
  getJSSDK: getJSSDK
}

  引入wx.js并初始化

// 引入
import sdk from '@/utils/wx'

// 初始化sdk完成后再加载地图,避免获取定位失败
sdk.getJSSDK(window.location.href.split('#')[0],{}).then(()=>{
  // 初始化地图
  this.initBMap()
})

 c> 调用微信sdk获取当前位置坐标

let that = this
wx.getLocation({
  type: 'gcj02',
  complete: function (res) {
    // res.longitude - 当前经度
    // res.latitude - 当前维度
  }
});

因微信获取的地图经纬度是腾讯地图的经纬度,直接放进百度地图使用定位会有较大偏差,故,当获取当微信当前的经纬度后需要转换一下再使用

 a > 安装gcoord

cnpm i gcoord --save-dev

 b > 引入

import gcoord from 'gcoord'

 c > 转换获得百度坐标

// 坐标转换
var result = gcoord.transform([res.longitude,res.latitude], gcoord.GCJ02, gcoord.BD09);
// 得到转换后的经纬度
that.wxLocalLng = result[0]
that.wxLocalLat = result[1]

 最后附上完整代码

<template>
  <div>
    <div>
      <input type="text" />
      <button>搜索</button>
    </div>
    <div ></div>
  </div>
</template>

<script>
import {loadBMap} from "../utils/map";
import wx from 'weixin-js-sdk'
import gcoord from 'gcoord'
// wx初始化
import sdk from '@/utils/wx'

export default {
  name: 'HelloWorld',
  data () {
    return {
      map: null,
      // 搜索
      searchVal: '',
      // 当前位置坐标
      localLng: '',
      localLat: '',
      // 微信当前位置坐标
      wxLocalLng: '',
      wxLocalLat: '',
    }
  },
  mounted(){
    // 删除标记事件
    window.delMarkFn=this.delMarkFn;
    // sdk
    sdk.getJSSDK(window.location.href.split('#')[0],{}).then(()=>{
      // 初始化地图
      this.initBMap()
    })
  },
  methods:{
    // 初始化地图
    initBMap () {
      const that = this
      /* 百度地图 */
      window.initBaiduMapScript = () =>{
        that.map = new BMap.Map('map-container');
        that.map.centerAndZoom(new BMap.Point(116.404, 39.928), 15);
        //开启鼠标滚轮缩放
        that.map.enableScrollWheelZoom(true);
        // 添加比例尺控件
        var scaleCtrl = new BMap.ScaleControl();
        that.map.addControl(scaleCtrl);
        // 添加比例尺控件
        var zoomCtrl = new BMap.NavigationControl();
        that.map.addControl(zoomCtrl);

        // 获取当前位置(导航用)
        var geolocation = new BMap.Geolocation();
        geolocation.getCurrentPosition(function (data) {
          if (this.getStatus() == BMAP_STATUS_SUCCESS) {
            // 当前坐标经纬度
            that.localLng = data.point.lng
            that.localLat = data.point.lat
            // 如果为微信内置浏览器,则当前位置需要微信授权定位
            if (that.wxLocalLng || that.wxLocalLat) {
              // 当前坐标经纬度
              that.localLng = that.wxLocalLng
              that.localLat = that.wxLocalLat
            }
          } else {
            console.log('无法定位到您的当前位置,导航失败,请手动输入您的当前位置!' + that.getStatus());
          }
        }, {
          enableHighAccuracy: true
        });

        // 回显标记
        that.addMarkFn(116.404, 39.928)
        // 点击地图添加标记
        that.map.addEventListener('click', function (e) {
          alert('点击了地图,点击经纬度为:' + e.point.lng + ',' + e.point.lat);
          that.addMarkFn(e.point.lng, e.point.lat)
        });
        // 搜索-建立一个自动完成的对象
        var ac = new BMap.Autocomplete({
          "input" : "suggestId",
          "location" : that.map
        });
        // 搜索-点击下拉列表后的事件
        ac.addEventListener("onconfirm", function(e) {
          var _value = e.item.value;
          that.searchVal = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
          // 搜索
          that.search();
        });
        // 监听地图加载完成后-关闭加载层
        that.map.addEventListener('tilesloaded', function () {

        });
      }
      // 加载地图
      loadBMap('initBaiduMapScript');
      // 获取微信位置
      that.getWxLocalPosition()
    },
    // 微信需授权后才可获取地理位置
    getWxLocalPosition(){
      let that = this
      wx.getLocation({
        type: 'gcj02',
        complete: function (res) {
          if(res.latitude){
            // 坐标转换
            var result = gcoord.transform([res.longitude,res.latitude], gcoord.GCJ02, gcoord.BD09);
            that.wxLocalLng = result[0]
            that.wxLocalLat = result[1]
          }
        }
      });
    },
    // 搜索-地图
    search(){
      const that = this
      //智能搜索
      var local = new BMap.LocalSearch(that.map, {
        onSearchComplete: ()=>{
          //获取第一个智能搜索的结果
          const pp = local.getResults().getPoi(0).point;
          that.map.centerAndZoom(pp, 18);
        }
      });
      local.search(that.searchVal);
    },
    // 添加地图标记
    addMarkFn(lng, lat){
      const that = this
      const localInfo = {
        lng,
        lat
      }
      // 创建标记图标
      // const myIcon = new BMap.Icon(this.markerImg, new BMap.Size(19, 24));
      // 创建点标记
      const point = new BMap.Point(lng, lat);
      // 创建Marker标注
      const marker = new BMap.Marker(point, {
        // enableDragging: true,
        // icon: myIcon
      });

      // 用所定位的经纬度查找所在地省市街道等信息
      const getLocationInfo = () => new Promise((resolve, reject)=>{ // 设置aa函数返回promise对象
        var gc = new BMap.Geocoder();
        gc.getLocation(point, function (rs) {
          if (rs.surroundingPois.length > 0) {
            localInfo.address =  rs.address+rs.surroundingPois[0].title;
          } else {
            localInfo.address = rs.address;
          }
          console.log(localInfo);//地址信息
          resolve(localInfo)
        });
      })
      getLocationInfo().then(res=>{
        var opts = {
          width : 100,     // 信息窗口宽度
          height: 100,     // 信息窗口高度
          title : '信息窗口标题-故宫博物馆' // 信息窗口标题
        }
        const tipHtml =
          "<p class='m0 font-12'>地址:"+localInfo.address+"</p>"+
          "<a href='http://api.map.baidu.com/marker?location="+lat+","+lng+"&title="+localInfo.address+"&content=内容介绍&mode=driving&output=html'>导航去这里</a>"+
          "<p class='m0 mt3 font-12'>" +
          "<span class='marker-del' onclick=delMarkFn('"+lng+"','"+lat+"')>删除</span>" +
          "</p>"
        // 创建信息窗口对象
        var infoWindow = new BMap.InfoWindow(tipHtml, opts);
        marker.addEventListener("click", function(){
          //开启信息窗口
          this.map.openInfoWindow(infoWindow, point);
          // 阻止冒泡
          window.event? window.event.cancelBubble = true : e.stopPropagation();
        });
      })
      // 在地图上添加点标记
      this.map.addOverlay(marker);
      // 设置标注
      var label = new BMap.Label("<span>故宫博物馆</span>",{offset:new BMap.Size(20,-10)});
      marker.setLabel(label);
    },

    // 删除地图标记
    delMarkFn(lng, lat){
      var point = new BMap.Point(lng, lat);
      var allOverlay = this.map.getOverlays();
      for(var j = 0;j<allOverlay.length;j++) {
        //删除指定经度的点
        if (allOverlay[j].toString()=="[object Marker]" && allOverlay[j].getPosition().lng == lng && allOverlay[j].getPosition().lat == lat ) {
          this.map.removeOverlay(allOverlay[j]);
        }
      }
      this.map.closeInfoWindow(point)
    },
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
#map-container{
  height: 100vh;
}
/deep/.marker-del{
  float: right;
  color: #f00;
}
/deep/.BMap_bubble_title{
  font-size: 14px;
  font-weight: bold;
  white-space: normal!important;
  line-height: 15px!important;
  margin-bottom: 3px;
}
/deep/.BMap_bubble_content{
  font-size: 12px;
}
</style>

有疑问或建议可留言交流,感谢支持!