uni-app中使用markers画点时,操作数组中同一索引,会导致两个点都显示在屏幕上
uni-app中使用markers画点时,操作数组中同一索引,会导致两个点都显示在屏幕上
| 开发环境 | 版本号 | 项目创建方式 |
|---|---|---|
| Windows | 10.0.18363.1441 | HBuilderX |
| 3.1.11 |
产品分类:uniapp/App
PC开发环境操作系统:Windows
手机系统:Android
手机系统版本号:Android 10
手机厂商:模拟器
手机机型:华为
页面类型:nvue
打包方式:云端
示例代码:
<map :markers="covers">
</map>
data() {
return {
covers: [
{
latitude: null,
longitude: null,
},
}
}
onLoad(){
setInterval(() => {
//每秒获取自己的位置
this.getUserInfo();
}, 1000);
}
methods: {
getUserInfo() {
let that = this;
uni.getLocation({
type: "wgs84",
success: function (res) {
that.covers[0].latitude = res.latitude;
that.covers[0].longitude = res.longitude;
that.covers = [...that.covers];
},
});
},
}
操作步骤:
```javascript
<map :markers="covers">
</map>
data() {
return {
covers: [
{
latitude: null,
longitude: null,
},
}
}
onLoad(){
setInterval(() => {
//每秒获取自己的位置
this.getUserInfo();
}, 1000);
}
methods: {
getUserInfo() {
let that = this;
uni.getLocation({
type: "wgs84",
success: function (res) {
that.covers[0].latitude = res.latitude;
that.covers[0].longitude = res.longitude;
that.covers = [...that.covers];
},
});
},
}
预期结果:
```javascript
<map :markers="covers">
</map>
data() {
return {
covers: [
{
latitude: null,
longitude: null,
},
}
}
onLoad(){
setInterval(() => {
//每秒获取自己的位置
this.getUserInfo();
}, 1000);
}
methods: {
getUserInfo() {
let that = this;
uni.getLocation({
type: "wgs84",
success: function (res) {
that.covers[0].latitude = res.latitude;
that.covers[0].longitude = res.longitude;
that.covers = [...that.covers];
},
});
},
}
实际结果:
```javascript
<map :markers="covers">
</map>
data() {
return {
covers: [
{
latitude: null,
longitude: null,
},
}
}
onLoad(){
setInterval(() => {
//每秒获取自己的位置
this.getUserInfo();
}, 1000);
}
methods: {
getUserInfo() {
let that = this;
uni.getLocation({
type: "wgs84",
success: function (res) {
that.covers[0].latitude = res.latitude;
that.covers[0].longitude = res.longitude;
that.covers = [...that.covers];
},
});
},
}
bug描述:
更多关于uni-app中使用markers画点时,操作数组中同一索引,会导致两个点都显示在屏幕上的实战教程也可以访问 https://www.itying.com/category-93-b0.html
1 回复
更多关于uni-app中使用markers画点时,操作数组中同一索引,会导致两个点都显示在屏幕上的实战教程也可以访问 https://www.itying.com/category-93-b0.html
这个问题是由于数组引用未更新导致的。在uni-app中,直接修改数组元素的属性不会触发视图更新,即使使用了扩展运算符创建新数组。
问题出现在这里:
that.covers[0].latitude = res.latitude;
that.covers[0].longitude = res.longitude;
that.covers = [...that.covers];
虽然最后创建了新数组,但数组中的对象仍然是同一个引用,map组件可能无法正确检测到marker位置的变化。
解决方案是创建一个全新的对象:
getUserInfo() {
let that = this;
uni.getLocation({
type: "wgs84",
success: function (res) {
that.covers = [{
latitude: res.latitude,
longitude: res.longitude,
// 如果需要,可以添加其他必要的marker属性
id: 0,
iconPath: '/static/marker.png',
width: 30,
height: 30
}];
},
});
}
或者使用深拷贝的方式:
that.covers = [{
...that.covers[0],
latitude: res.latitude,
longitude: res.longitude
}];

