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

如何从Mapbox GL Geocoder的results事件中提取并存储坐标

实现方案

你可以直接在results事件的回调函数内完成坐标取值、变量存储和比对逻辑,示例代码如下:

// 可在回调外提前声明存储坐标的变量,方便其他逻辑调用
let savedCoordinate = []
// 你的预设比对坐标,按实际需求修改即可
const myPresetCoordinate = [121.4737, 31.2304]

geocoder.on('results', function(results) {
  // 方式一:获取config下proximity对应的坐标
  savedCoordinate = results.config.proximity

  // 方式二:获取features数组首个位置的center坐标(推荐,为搜索返回的首位结果坐标)
  if (results.features?.length) {
    savedCoordinate = results.features[0].center
  }

  console.log('已存储的坐标:', savedCoordinate)
  // 可直接在此处调用比对逻辑
  coordinateCompare(savedCoordinate, myPresetCoordinate)
})

// 坐标比对逻辑示例,可根据实际需求调整误差阈值
function coordinateCompare(target, preset) {
  // 允许的经纬度误差阈值,单位为度
  const offsetThreshold = 0.005
  const isLngMatch = Math.abs(target[0] - preset[0]) <= offsetThreshold
  const isLatMatch = Math.abs(target[1] - preset[1]) <= offsetThreshold
  if (isLngMatch && isLatMatch) {
    console.log('坐标匹配成功')
    // 匹配后的逻辑写在这里
  } else {
    console.log('坐标匹配失败')
    // 不匹配的逻辑写在这里
  }
}

注意事项

  • 如果需要在results事件回调外使用存储的坐标,要确保调用时results事件已经触发完成,否则会拿到初始空值,异步场景建议用回调或Promise处理取值逻辑。
  • 取features数组首项坐标时添加了可选链判断,避免无搜索结果时出现取值报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 20:45:06