调用百度api获取当前登录信息
1. 在index.html
引入
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=你自己的百度key"></script>
嫌麻烦就接着在 script里面写函数调用。
js code:
<script type="text/javascript">
//获取当前登录地点
function getAddressIp(){
const geolocation = new BMap.Geolocation();
let _this = this
geolocation.getCurrentPosition(function getinfo(position){
let city = position.address.city; //获取城市信息
let province = position.address.province; //获取省份信息
console.log("city:", city, 'province:', province, position)
}, function(e) {
_this.LocationCity = "定位失败"
}, {provider: 'baidu'});
}
getAddressIp()
</script>
打印结果:
2. 在vue页面的使用方法:
在自己想要得到信息的vue中
定义渲染属性
data () {
return {
LocationPCity: "", //正在定位所在省 + 市
}
}
Bmap依赖请引入 :
yarn add bmap
或者 npm install bmap
在vue.config.js: 加上这句
externals:{
'BMap': 'BMap' // 百度地图获取城市
}
然后重新启动项目
methods:{
//定义获取城市方法
city(){
const geolocation = new BMap.Geolocation();
var _this = this
geolocation.getCurrentPosition(function getinfo(position){
let city = position.address.city; //获取城市信息
let province = position.address.province; //获取省份信息
_this.LocationPCity = province + ' ' + city
console.log("LocationPCity:", _this.LocationPCity, position)
}, function(e) {
_this.LocationPCity = "定位失败"
}, {provider: 'baidu'});
},
}
mounted() {
this.city()
},
打印结果:
最后为了方便大家的沟通与交流请加QQ群: 625787746
请进QQ群交流:【IT博客技术分享群①】:正在跳转