You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何通过邮政编码查询地址?Google Maps API请求报错排查

解决Google Maps Web Services返回INVALID_REQUEST的问题

你现在遇到的问题核心是用错了API方法——你正在使用的Places Autocomplete API是用来做输入时的地址建议的,而不是获取指定邮政编码关联的完整地址列表。再加上参数搭配的冲突,才导致请求返回INVALID_REQUEST状态码。

问题拆解

  1. API用途不符:Autocomplete API的设计目标是接收用户输入的地址片段(比如正在输入的街道名、部分邮编),返回匹配的建议选项,而非查询完整邮政编码对应的所有关联地址。
  2. 参数重复冲突:你既在autocomplete的第一个参数传入了完整邮政编码,又在components里指定了Component.postalCode,这种重复的限制条件会让API无法正确解析请求逻辑,触发无效请求的报错。

正确解决方案:改用Geocoding API

要获取指定邮政编码对应的地址列表,应该使用Geocoding API——这个API专门负责地址与地理坐标的相互转换,同时会返回匹配的完整地址详情。

下面是调整后的可用代码:

import 'package:google_maps_webservice/geocoding.dart';

final _geocoding = GoogleMapsGeocoding(apiKey: '<API-Key>');

void main() async {
  final postalCode = 'WC2N 5DU';
  final response = await _geocoding.searchByAddress(
    postalCode,
    components: [
      Component(Component.country, 'GB'),
    ],
  );

  if (response.isOkay) {
    for (GeocodingResult result in response.results) {
      print('完整地址:${result.formattedAddress}');
      // 还可以提取更细分的地址组件(比如街道、城市、行政区等)
      for (var component in result.addressComponents) {
        print('${component.types.join(',')}: ${component.longName}');
      }
    }
  } else {
    print('请求失败:${response.status}');
    print('错误详情:${response.errorMessage}');
  }
}

补充:如果确实需要用Autocomplete(输入建议场景)

如果你是想做邮政编码的输入联想(比如用户输入部分邮编时给出建议),可以调整参数解决无效请求问题:移除components里的Component.postalCode限制,只保留国家过滤,同时传入部分邮编作为查询词,示例如下:

import 'package:google_maps_webservice/places.dart';

final _places = GoogleMapsPlaces(apiKey: '<API-Key>');

void main() async {
  final partialPostalCode = 'WC2N';
  final response = await _places.autocomplete(
    partialPostalCode,
    components: [Component(Component.country, 'GB')],
    location: Location(51.50721, -0.12827),
    radius: 5000, // 可选:缩小搜索范围,优先返回附近匹配项
  );

  if (response.isOkay) {
    for (Prediction prediction in response.predictions) {
      print(prediction.description);
    }
  } else {
    print(response.status);
    print(response.errorMessage);
  }
}

但务必记住:Autocomplete不是获取完整邮编对应地址列表的最佳工具,Geocoding API才是对应场景的正确选择。

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

火山引擎 最新活动