vue中使用百度地图获取地理位置

1.首先要在百度地图官网(http://lbsyun.baidu.com/)上面新建实例,获取百度地图的密钥:ak
第一种方法在index.html页面引入百度地图的js

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

3.在你的项目webpack.base.conf.js文件里面加上下面这句:

4.在需要的页面使用的页面直接引入:

import BMap from "BMap";
// 获取当前定位
    getCurrentCity() {
      let geolocation = new BMap.Geolocation(); // 创建百度地理位置实例
      geolocation.getCurrentPosition(function (e) {
        if (this.getStatus() == BMAP_STATUS_SUCCESS) {
          // 百度 geolocation 的经纬度属性不同,此处是 point.lat 而不是 coords.latitude
          let point = new BMap.Point(e.point.lng, e.point.lat);
          let gc = new BMap.Geocoder();
          gc.getLocation(point, function (rs) {
            let currentPosition = rs.point;
            let addComp = rs.addressComponents; // 返回的结果
            let address = addComp.city; // 拼接地址
          });
        } else {
          console.log(this.getStatus());
        }
      });
    },

5.注意,如果你的vue页面需要使用webview内嵌在微信小程序里面的话,会出现在ios里面不能使用的情况。

引入地图js的方法二:
单页面引入js,不全局使用。这时候我们可以动态创建一个js标签,引入到要使用的页面:
新建一个map.js文件

export default {
    init: function (){
    const AK = '';//百度地图的密钥
    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);
    });
    }
 }

在使用的页面引入:

import map from 'common/js/map.js'
//使用时:map.init().then(()=>{})
 getCurrentCity() {
      map.init().then(()=>{
         let _this = this;
        let geolocation = new BMap.Geolocation(); // 创建百度地理位置实例,代替 navigator.geolocation
         geolocation.getCurrentPosition(function (e) {
        if (this.getStatus() == BMAP_STATUS_SUCCESS) {
          // 百度 geolocation 的经纬度属性不同,此处是 point.lat 而不是 coords.latitude
          let point = new BMap.Point(e.point.lng, e.point.lat);
          let gc = new BMap.Geocoder();
          gc.getLocation(point, function (rs) {
            let currentPosition = rs.point;
            let addComp = rs.addressComponents; 
          });
        } else {
          console.log(this.getStatus());
        }
      });
      })
    },
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值