vue获取当前位置

文章描述:

Vue百度地图获取当前位置

 

百度地图开发平台

Referer白名单添加本地访问端口

npm安装

cnpm install vue-baidu-map --save

 

引入及使用

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

myBMap.js

export default {
    init: function () {
        const AK = '';  //你的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);
        });
    }
}

 

Vue文件

<template>
  <div>
	  
  </div>
</template>

<script>
import Vconsole from "vconsole";
import myBMap from "../utils/myBMap";
export default {
  data() {
    return {

    }
  },
  created() {
    this.getLocation();
  },
  methods: {
	    getLocation() {
			const vconsole = new Vconsole();
			vconsole;
			//Toast("如长时间未获取办理区域请手动选择");
			myBMap.init().then(() => {
				let that = 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) {
						
					  console.log(rs);
					  //<<<<<<<<<<<<<<<<需要的位置信息在这获取
					});
				  } else {
					Toast("定位失败,请手动选择区域或重新定位");
					this.showloading = false;
				  }
				});
			});
	    },
  }
}
</script>
<style scoped lang="scss"></style>

 

 

访问:http://localhost:8080/

发布时间:2023/10/06

发表评论