You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用MapBox绘制坐标时经纬度返回undefined问题求助

问题解决:MapBox坐标longitude/latitude为undefined的原因及修复

你的问题出在数据包装的层级错误,导致targetElements接收的不是单个位置对象,而是嵌套的数组,所以无法直接解构出longitude和latitude。

具体问题分析

在targetLocations方法里,你把每个位置对象用数组包裹后再push到data中:

this.coordinates = [store.state.location.locations[i]]
data.push(this.coordinates)

这会让data的结构变成[[location1], [location2], ...],而非预期的[location1, location2, ...]。当data.map(this.targetElements)执行时,targetElements的参数index实际是[locationObj]这样的数组,而非单个位置对象——数组本身没有longitude、latitude这些属性,所以解构出来自然是undefined。

修复方案

直接将位置对象push到data中,不要额外包裹数组:

targetLocations() {
  const timer = setInterval(() => {
    // 每次定时执行时重置data,避免重复累加
    const data = [...store.state.location.locations];
    this.map.getSource('data-source').setData({
      "type": "FeatureCollection",
      "features": data.map(this.targetElements)
    });
  }, 1000);
},
targetElements(location) {
  // 现在location是单个位置对象,可以正常解构
  const { longitude, latitude, userName, dateTimeStored } = location;
  return {
    "type": "Feature",
    "properties": {
      'description': `PID: ${userName}<br />Lng/Lat: ${longitude} / ${latitude}<br />Captured At: ${dateTimeStored}`,
      'name': userName,
      'capturedAt': dateTimeStored,
    },
    "geometry": {
      "type": "Point",
      "coordinates": [longitude, latitude]
    }
  };
},

额外优化点

  1. 每次定时执行时要重置data,否则原代码会不断往data里push重复数据,导致地图上标记越来越多。
  2. 用模板字符串替代字符串拼接,代码更简洁易读。

内容的提问来源于stack exchange,提问作者NoobAmI

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 16:02:42