Google Maps loadGeoJSON后调用getGeometry.get()出现latlng丢失问题
谷歌地图门店定位器开发坐标丢失问题排查
背景说明
- 当前学习教程:谷歌官方门店定位器教程
- 对应代码仓库:google-maps-simple-store-locator
- 涉及文件:
app.js - 关联函数:
initMap()、calculateDistances()
问题描述
地图加载正常,所有点位可正常渲染,说明map.data.loadGeoJSON功能运行正常,且已确认JSON文件中坐标存在。但使用搜索/自动完成功能时,坐标值无法正常获取:
- 第218行将
map.data作为参数传入计算距离函数:
const rankedStores = await calculateDistances(map.data, originLocation);
calculateDistances函数中解析点位坐标时,console.log(storeLoc)没有几何坐标输出:LatLng对象和对应的latlng属性存在,但没有实际坐标值,storeNum打印结果正常。
async function calculateDistances(data, origin) { const stores = []; const destinations = [] // 构建门店ID和目的地的并行数组 data.forEach((store) => { const storeNum = store.getProperty('storeid'); const storeLoc = store.getGeometry().get(); console.log(storeLoc); stores.push(storeNum); destinations.push(storeLoc); }); }
相关截图
- 截图A:console.log(store.storeLoc)输出结果

- 截图B:console.log(store.toUrlValue(6))输出结果

解决方案
这个问题的核心原因是map.data.loadGeoJson()是异步执行方法,你触发搜索计算距离时,GeoJSON的几何属性还没有完成完全反序列化,控制台打印的LatLng对象是后续控制台异步填充的快照,实际代码执行时坐标值还没有生成。按以下步骤修改即可解决:
- 把
loadGeoJson包装成Promise,确保所有操作map.data的逻辑都在GeoJSON加载完成后执行:
// 在initMap函数内部添加封装方法 const loadGeoJsonPromise = (url) => { return new Promise((resolve) => { map.data.loadGeoJson(url, null, (loadedFeatures) => resolve(loadedFeatures)); }); } // initMap中加载GeoJSON的逻辑改为await等待加载完成 async function initMap() { // 省略地图实例初始化、自动完成绑定等逻辑 await loadGeoJsonPromise('你的GeoJSON文件路径'); // 所有依赖map.data的逻辑(比如搜索按钮点击事件绑定)都放在这行之后 }
- 优化坐标读取逻辑,增加类型判断,主动调用
lat()、lng()方法触发值的计算:
async function calculateDistances(data, origin) { const stores = []; const destinations = [] data.forEach((store) => { const storeNum = store.getProperty('storeid'); const geometry = store.getGeometry(); // 先判断几何类型为Point再取值 if (geometry.getType() === 'Point') { const storeLoc = geometry.get(); // 主动取值,避免异步惰性求值问题 console.log('门店坐标', storeLoc.lat(), storeLoc.lng()); stores.push(storeNum); destinations.push(storeLoc); } }); // 省略后续距离计算逻辑 }
- 排查项目中是否有其他遍历
map.data的逻辑,检查有没有误修改、删除feature的geometry属性的操作。
内容的提问来源于stack exchange,提问作者user3795286
相关产品推荐
相关产品推荐

