uni app +vue 引用 百度地图API取位置,VUE用百度地图获取当前位置(城市)

uni app +vue 引用 百度地图API取位置,VUE用百度地图获取当前位置(城市)
 
1.在index.html 引入 百度js
<script src="http://api.map.baidu.com/api?v=2.0&ak=你的密钥" type="text/javascript"></script>
 
2.创建js文件,放入以下代码:
 
export default {
    init: function () {
        const AK = "lyFvtNiZ2fH1jWqGIRMAxDwDbMwvXgsv";
        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);
        });
    }
}

3.需要用的组件里开始引用和调用
写在方法里,在mounted里调用–下面代码不可少

  mounted() {
    var isWeixn = this.is_weixn();
    if (isWeixn) {
      this.getCity();
    }
  },
  methods: {
    getCity() {
      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)
              },
              function (e){
                that.LocationCity = '定位失败';
                console.log('定位失败')
              },
              {provider: 'baidu'}
            )
          })
    },
}    

 

posted @ 2020-06-17 09:55  假装学习  阅读(8901)  评论(0编辑  收藏  举报