在开发uniAPP 的时候,在使用 getLocation 这个API 给Vue的data赋值时候报这个错误
源代码如下
getLocation(){
let _this = this
uni.getLocation({
type: 'wgs84',
success: function (res) {
var point = new _this.BMap.Point(res.longitude,res.latitude);
var gc = new _this.BMap.Geocoder();
gc.getLocation(point, function(rs){
rs = JSON.parse(JSON.stringify(rs))
this.province = rs.addressComponents.province;
this.city = rs.addressComponents.city;
this.county = rs.addressComponents.district || rs.addressComponents.city;
});
},
fail: function (res) {
console.log(res);
},
});
},
浏览器报错 Uncaught TypeError: Cannot set properties of undefined (setting 'province')
看了下 这是this指向的问题 重新定义this 就可以了
改后的代码
getLocation(){
let _this = this
uni.getLocation({
type: 'wgs84',
success: function (res) {
var point = new _this.BMap.Point(res.longitude,res.latitude);
var gc = new _this.BMap.Geocoder();
gc.getLocation(point, function(rs){
rs = JSON.parse(JSON.stringify(rs))
_this.province = rs.addressComponents.province;
_this.city = rs.addressComponents.city;
_this.county = rs.addressComponents.district || rs.addressComponents.city;
});
},
fail: function (res) {
console.log(res);
},
});
},
另需要在Vue项目中获取定位地址信息的,可以参照我的这篇文章
https://blog.csdn.net/AisinGioroGouzi/article/details/124105722