Vue利用百度地图初始化页面定位

结果展示

获取百度ak

引入控件

  • npm install vue-baidu-map --save

main.js中引入

import Vue from 'vue';
import BaiduMap from 'vue-baidu-map'
Vue.use(BaiduMap, {
    ak: '申请的百度地图秘钥'
})

页面控件

<div>
  <baidu-map :center="center" :zoom="zoom" :scroll-wheel-zoom="true" style="height: 65vh" @ready="handler"
             @click="getClickInfo">
    <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
    <bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_RIGHT" :showAddressBar="true" :autoLocation="true"></bm-geolocation>
    <bm-city-list anchor="BMAP_ANCHOR_TOP_LEFT"></bm-city-list>
  </baidu-map>
</div>

js部分

<script>
  export default {
    data() {
      return {
        center: {lng: 0, lat: 0}, //经纬度
        zoom: 13 //地图展示级别
      };
    },
    methods: {
      handler({BMap, map}) {
        this.zoom = this.zoom;
        let self = this;

        //关键词定位
        map.centerAndZoom("太原", 11);

        //浏览器位置定位
        // var geolocation = new BMap.Geolocation();
        // geolocation.getCurrentPosition(function (r) {
        //   let pi = 3.141592653589793 * 3000.0 / 180.0;
        //   let x = r.longitude;
        //   let y = r.latitude;
        //   let z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * pi);
        //   let theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * pi);
        //
        //   self.center.lng = z * Math.cos(theta) + 0.0065;
        //   self.center.lat = z * Math.sin(theta) + 0.006;
        // }, {enableHighAccuracy: true})

      },
      getClickInfo(e) {
        this.center.lng = e.point.lng;
        this.center.lat = e.point.lat;
      },
    }
  }
</script>

注意事项

  1. 页面地图控件必须指定高度
  2. 浏览器定位有误差
Logo

前往低代码交流专区

更多推荐