fl_geocoder
一个 Flutter 包,用于使用 Google Maps Platform Geocoding API 进行**正向**和**反向**地理编码。该包提供了 API 响应中更详细的数据,例如地址组件、几何信息、地点 ID 和状态码。
? 先决条件
在使用此包之前,您需要在项目中拥有已启用结算的账户,并在 Google Maps Platform 上启用 Geocoding API。
? 安装
dependencies:
fl_geocoder: ^0.0.1
⚙ 导入
import 'package:fl_geocoder/fl_geocoder.dart';
?️ 用法
创建 FlGeocoder 的一个实例以访问可用的地理编码功能。您必须提供一个有效的 API 密钥才能使函数按预期工作。另一方面,此包提供了错误消息,您可以在其中进行调试并找出原因。
final geocoder = const FlGeocoder('YOUR-API-KEY');
GestureDetector(
onTap: () async {
final coordinates = Location(40.714224, -73.961452);
final results = await geocoder.findAddressesFromLocationCoordinates(
location: coordinates,
useDefaultResultTypeFilter: isFiltered,
// resultType: 'route', // Optional. For custom filtering.
);
},
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 8.0, vertical: 4.0),
margin: const EdgeInsets.symmetric(horizontal: 8.0),
decoration: const BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.all(Radius.circular(5.0))),
child: Text('Search',
style: const TextStyle(color: Colors.white)),
),
),
FlGeocoder
FlGeocoder 类包含三个不同的地理编码功能。
1. findAddressesFromLocationCoordinates
根据给定的 [Location] 搜索相应的地址。
| 参数 | 类型 | 描述 |
|---|---|---|
| location | Location | 必需值,指定您希望从中获取最近、可读地址的位置。 |
| resultType | String? | 一个或多个地址类型的过滤器,用管道符(|)分隔。如果参数包含多个地址类型,API 将返回所有匹配任一类型的地址。 |
| useDefaultResultTypeFilter | 布尔值 | 一个可选参数,用于检查是否使用此包提供的默认过滤器类型,即 `street_number |
2. findAddressesFromAddress
搜索与给定字符串 [address] 查询匹配的可用地址列表。
| 参数 | 类型 | 描述 |
|---|---|---|
| address | 字符串 | 必需的参数,地理编码的特定区域将以此为基础。 |
2. findAddressesFromPlaceId
搜索与给定地点 ID 匹配的可用地址列表。
| 参数 | 类型 | 描述 |
|---|---|---|
| id | 字符串 | 必需的参数,[place] ID 在 Google Places 数据库和 Google Maps 中唯一标识一个地点。 |
❌ 错误处理
GeocodeFailure 为您提供了遇到错误的详细人类可读解释。
final latitude = double.parse(latitudeController.text);
final longitude = double.parse(longitudeController.text);
final coordinates = Location(latitude, longitude);
try {
final results =
await widget.geocoder.findAddressesFromLocationCoordinates(
location: coordinates,
useDefaultResultTypeFilter: isFiltered,
);
} on GeocodeFailure catch (e) {
// Do some debugging or show an error message.
log(e.message ?? 'Unknown error occured.');
} catch (_) {
// Do some debugging or show an error message.
log('Generic failure occured.');
}
? Bug/需求
如果您遇到任何问题,请随意提出 issue。如果您觉得库缺少某个功能,请在 Github 上提交一个 ticket,我们会进行查看。也欢迎提交 Pull Request。
? 许可证
MIT 许可


