添加FieldMask后Flutter调用Google Maps Places API获取坐标失败
问题解决:添加FieldMask后无法通过Place ID获取坐标
问题原因
当你为Google Places API添加FieldMask后,API只会返回你明确指定的字段。你的原代码在获取Place详情时,没有指定geometry.location和name这些需要用到的字段,导致details.result.geometry始终为null,后续获取坐标的逻辑根本无法执行。
解决方案
调用getDetailsByPlaceId方法时,必须通过fields参数指定需要返回的字段,把你代码里用到的geometry.location和name加进去——这样既能满足计费优化的需求,又能拿到所需数据。
修改后的完整代码
Future setCustomMarker(String placeId) async { final details = await GoogleMapsPlaces( apiKey: 'Api key', ).getDetailsByPlaceId( placeId, // 指定需要返回的字段,按需添加避免额外计费 fields: ['geometry.location', 'name'], ); if (details.result.geometry != null) { final location = details.result.geometry!.location; double lat = location.lat; double lng = location.lng; LatLng destination = LatLng(lat, lng); endLocation = destination; // 生成自定义标记图标 BitmapDescriptor customIcon = await CustomMapMarker.getCustomMarkerIcon( Colors.green, // 填充色 Colors.black, // 边框色 52.0, // 标记尺寸 ); setState(() { isTextFieldVisible = false; _markers.clear(); _markers.add( Marker( markerId: MarkerId(placeId), position: destination, infoWindow: InfoWindow( snippet: details.result.name, title: 'Your destination ', ), icon: customIcon, // 设置自定义图标 ), ); }); mapController.animateCamera( CameraUpdate.newLatLngZoom(destination, 14.5), ); } }
注意事项
- FieldMask的字段必须严格匹配Google Places API的官方字段名,你可以根据实际需求增减字段,比如需要地址信息时可以添加
formatted_address。 - 只请求必要字段才能有效减少API计费,避免不必要的开销。
内容的提问来源于stack exchange,提问作者sangram jit samanta
相关产品推荐
相关产品推荐

