如何从Google Maps API返回的Bounds中获取经纬度坐标?
解决Google Maps API Bounds坐标获取问题
嘿,我明白你遇到的困扰了!你看到的_.L {lat: ƒ, lng: ƒ}其实是Google Maps API返回的LatLng对象,它的纬度和经度不是直接的属性,而是需要通过调用方法来获取的——这就是你之前尝试无效的原因!
正确的获取方式
你只需要对getNorthEast()和getSouthWest()返回的对象调用lat()和lng()方法就能拿到具体的坐标值了,代码示例如下:
// 假设vr是你的Bounds实例 const northEast = vr.getNorthEast(); const neLat = northEast.lat(); // 获取东北边界纬度 const neLng = northEast.lng(); // 获取东北边界经度 const southWest = vr.getSouthWest(); const swLat = southWest.lat(); // 获取西南边界纬度 const swLng = southWest.lng(); // 获取西南边界经度 // 打印验证 console.log(`东北坐标:${neLat}, ${neLng}`); console.log(`西南坐标:${swLat}, ${swLng}`);
为什么不要直接访问内部属性?
你之前看到的pa、ka、g、h这些是Google Maps API代码压缩后的变量名,不同版本的API可能会改变这些命名,直接依赖它们会导致代码在API更新后失效。官方提供的getNorthEast()、getSouthWest()以及LatLng对象的lat()、lng()方法才是稳定可靠的接口。
额外小技巧:一次性获取所有边界值
如果你想快速拿到四个边界的数值,也可以这样写:
const bounds = vr.getBounds(); const south = bounds.getSouthWest().lat(); const west = bounds.getSouthWest().lng(); const north = bounds.getNorthEast().lat(); const east = bounds.getNorthEast().lng(); console.log(`南: ${south}, 西: ${west}, 北: ${north}, 东: ${east}`);
内容的提问来源于stack exchange,提问作者golimoli
相关产品推荐
相关产品推荐

