百度获取定位 位置

首先我用的框架是Vue+vant 写的h5页面

一:在main.js中

import BaiduMap from 'vue-baidu-map'
Vue.use(BaiduMap,{
  ak:'KtmkN07XXXXXXXXXmiKbWp9B2'//自己去百度API申请,免费的
})
Vue.config.productionTip = false

 

二:在index.html中

 <script type="text/javascript" src="https://api.map.baidu.com/api?v=2.0&ak=KtmkN076TmqTs6NqU4Bx1qHmiKbWp9B2"></script>

 

 

 

 三:在需要用户信息的页面

  mounted() {
    this.city();
  },
  methods: {
    city() {
      map.init().then((BMap) => {
        const locationCity = new BMap.Geolocation();
        var that = this;
        locationCity.getCurrentPosition(
          function getinfo(options) {
            let city = options.address.city;
            that.LocationCity = city;
            console.log(options, 9);
            this.latitude = options.latitude;
            this.longitude = options.longitude;
            this.accuracy = options.accuracy
          },
          function (e) {
            console.log("2", e);
            that.LocationCity = "定位失败";
            console.log("定位失败");
          },
          { provider: "baidu" }
        );
      });
    },

 

 

 

 四:引入的js文件

export default {
  init: function (){
  const AK = "KtmkN076TmqTs6NqU4Bx1qHmiKbWp9B2";
  const BMap_URL = 'https://api.map.baidu.com/api?v=2.0&ak='+ AK +"&s=1&callback=onBMapCallback";
  return new Promise((resolve, reject) => {
  // 如果已加载直接返回
  if(typeof BMap !== "undefined") {
  resolve(BMap);
  return true;
  }
  // 百度地图异步加载回调处理
  window.onBMapCallback = function () {
  resolve(BMap);
  };
  let getCurrentCityName = function () {
  return new Promise(function (resolve, reject) {
  let myCity = new BMap.LocalCity()
  myCity.get(function (result) {
  resolve(result.name)
  })
  })
  }
  // 插入script脚本
  let scriptNode = document.createElement('script');
  scriptNode.setAttribute('type', 'text/javascript');
  scriptNode.setAttribute('src', BMap_URL);
  document.body.appendChild(scriptNode);
  });
  }
  }

  

 

posted @ 2020-07-30 15:58  丫玉  阅读(399)  评论(0编辑  收藏  举报