效果:
IP定位(精准)
浏览器定位和SDK辅助定位返回经纬度不精准
要点:
- 入口文件引入(需要申请百度ak)
<script type="text/javascript" src="https://api.map.baidu.com/api?v=2.0&ak=vaVH6Ls3Tisndi940ma2keNeGSm0UvH4"></script>
- 代码中调用百度API
IP定位(精准)
<div @click="getLocation">IP定位</div>
...
getLocation() {
// 获取当前定位城市--IP定位
var BMap = window.BMap;
var myCity = new BMap.LocalCity();
let _this = this;
myCity.get(r => {
console.log('经纬度信息',r)
// 根据经纬度获取省和市
var gc = new BMap.Geocoder();
var pointAdd = new BMap.Point(r.center.lng, r.center.lat);
gc.getLocation(pointAdd, function(rs) {
//获取城市地址
console.log('城市信息',rs);
});
});
}
浏览器定位(有误差)
<div @click="getGeolocation">浏览器定位</div>
...
getGeolocation() {
var geolocation = new BMap.Geolocation();
geolocation.getCurrentPosition(function(r) {
console.log('经纬度信息',r)
});
}
SDK辅助定位(有误差)
<div @click="getGeolocationSDK">SDK辅助定位</div>
...
getGeolocationSDK() {
var geolocation = new BMap.Geolocation();
// 开启SDK辅助定位
geolocation.enableSDKLocation();
geolocation.getCurrentPosition(function(r) {
console.log("经纬度信息", r);
});
}
示例:
<template>
<div class="bmap">
<div class="cantent">
<div
class="btn"
@click="getLocation"
>IP定位</div>
<div
class="showinfo"
v-if="local.lat"
>
<div>lat:{{this.local.lat}}</div>
<div>lng:{{this.local.lng}}</div>
</div>
<div
class="btn"
@click="getGeolocation"
>浏览器定位</div>
<div
class="btn"
@click="getGeolocationSDK"
>SDK辅助定位</div>
</div>
</div>
</template>
<script>
export default {
name: "bmap",
data() {
return {
local: {
lat: "",
lng: ""
}
};
},
methods: {
// IP定位
getLocation() {
// 获取当前定位城市--IP定位
var BMap = window.BMap;
var myCity = new BMap.LocalCity();
let _this = this;
myCity.get(r => {
console.log("经纬度信息", r);
this.local.lat = r.center.lat;
this.local.lng = r.center.lng;
// 根据经纬度获取省和市
var gc = new BMap.Geocoder();
var pointAdd = new BMap.Point(r.center.lng, r.center.lat);
gc.getLocation(pointAdd, function(rs) {
//获取城市地址
console.log("城市信息", rs);
});
});
},
// 浏览器定位
getGeolocation() {
var geolocation = new BMap.Geolocation();
geolocation.getCurrentPosition(function(r) {
console.log("经纬度信息", r);
});
},
// SDK辅助定位
getGeolocationSDK() {
var geolocation = new BMap.Geolocation();
// 开启SDK辅助定位
geolocation.enableSDKLocation();
geolocation.getCurrentPosition(function(r) {
console.log("经纬度信息", r);
});
}
}
};
</script>
<style lang="less" scoped>
.bmap {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
.cantent {
.btn {
background: rgb(175, 70, 87);
color: #fff;
padding: 5px 10px;
border-radius: 5px;
cursor: pointer;
margin-top: 20px;
}
.showinfo {
margin-top: 10px;
div {
margin: 10px 0;
}
}
}
}
</style>