Mapbox Flutter地图切换至美国区域时纬度越界报错求助
解决Mapbox Flutter中坐标顺序错误导致的纬度范围异常问题
问题核心分析
报错提示latitude must be between -90 and 90 but was -122.419415,说明你把美国区域的经度值(-122.419415)错误当成纬度传入,超出了纬度的合法区间[-90, 90]。
- 欧洲区域未报错的原因:欧洲经度多在0°附近,纬度在40°-60°之间,即使坐标颠倒,传入的"纬度"(实际是经度)仍在合法范围内,不会触发校验;但美国经度为负且绝对值大于90,颠倒后直接触发校验失败。
- 你之前尝试翻转坐标无效,大概率是因为通过字符串切割解析坐标的方式已经提前搞混了经纬度顺序,后续翻转只是二次错误。
解决方案
- 废弃字符串切割解析坐标的方式:直接从
CameraState对象提取经纬度,彻底避免字符串处理带来的顺序混乱和格式错误。 - 严格遵循Mapbox坐标规则:
Position构造函数的参数顺序为**[经度(longitude), 纬度(latitude)]**,必须保证传入顺序正确。
修改后的代码示例
mapboxMap?.getCameraState().then((cameraState) { // 直接从CameraState提取经纬度,无需字符串切割 final center = cameraState.center; final latitude = center.latitude; final longitude = center.longitude; mapboxMap?.coordinateBoundsZoomForCamera(CameraOptions( center: Point( coordinates: Position( longitude, // 经度在前 latitude, // 纬度在后 ) ).toJson(), )).then((boundsResult) async { final north = boundsResult.bounds.northeast["coordinates"]; final south = boundsResult.bounds.southwest["coordinates"]; // 后续业务逻辑... }); });
如果cameraState.center是Point类型,调整经纬度提取方式:
final center = cameraState.center as Point; final longitude = center.coordinates[0]; // Point的coordinates默认顺序为[经度, 纬度] final latitude = center.coordinates[1];
内容的提问来源于stack exchange,提问作者nologic
相关产品推荐
相关产品推荐

