Flutter地理编码插件fl_geocoder的使用
Flutter地理编码插件fl_geocoder的使用
fl_geocoder
一个用于使用Google Maps平台地理编码API进行正向和反向地理编码的Flutter包。此包提供了API响应中更详细的数据,如地址组件
、几何形状
、地点ID
和状态码
。
🎯 预备条件
在开始使用此包之前,您需要在Google Maps平台创建一个具有账单账户并启用地理编码API的项目。
🔨 安装
在pubspec.yaml
文件中添加以下依赖:
dependencies:
fl_geocoder: ^0.0.1
⚙ 导入
在您的Dart文件中导入该包:
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', // 可选。自定义过滤。
);
},
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? | 可选参数,用于过滤一个或多个地址类型,用管道符( |
useDefaultResultTypeFilter | bool | 可选参数,检查是否使用此包提供的默认过滤类型(例如street_number )。 |
2. findAddressesFromAddress
根据给定的字符串address
查询搜索可用的地址列表。
参数 | 类型 | 描述 |
---|---|---|
address | String | 必需参数,指定地理编码特定区域的基础。 |
3. findAddressesFromPlaceId
根据给定的地点ID搜索可用的地址列表。
参数 | 类型 | 描述 |
---|---|---|
id | String | 必需参数,地点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) {
// 进行调试或显示错误信息。
log(e.message ?? '未知错误发生。');
} catch (_) {
// 进行调试或显示错误信息。
log('通用失败发生。');
}
🐞 Bug/请求
如果您遇到任何问题,请随时提出问题。如果您认为库缺少功能,请在Github上提交一个ticket,我们会考虑。也欢迎提交Pull Request。
📃 许可证
MIT许可证
完整示例
下面是完整的示例代码:
import 'package:example/demo/utils.dart';
import 'package:example/demo/views/demo_page.dart';
import 'package:fl_geocoder/fl_geocoder.dart';
import 'package:flutter/material.dart';
const myApiKey = 'YOUR-API-KEY-HERE';
void main() {
final geocoder = FlGeocoder(myApiKey);
runApp(MyApp(geocoder));
}
class MyApp extends StatelessWidget {
const MyApp(this.geocoder, {Key? key}) : super(key: key);
final FlGeocoder geocoder;
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
scaffoldMessengerKey: globalScaffoldMessengerKey,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: DemoPage(geocoder),
);
}
}
更多关于Flutter地理编码插件fl_geocoder的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter地理编码插件fl_geocoder的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是一个关于如何在Flutter项目中使用fl_geocoder
插件的示例代码。这个插件允许你将地理坐标(经纬度)转换为地址(反向地理编码),或者将地址转换为地理坐标(正向地理编码)。
首先,确保你已经在pubspec.yaml
文件中添加了fl_geocoder
依赖:
dependencies:
flutter:
sdk: flutter
fl_geocoder: ^0.0.2 # 请注意版本号,这里使用的是示例版本号,实际使用时请检查最新版本
然后运行flutter pub get
来获取依赖。
接下来,你可以在你的Flutter项目中使用这个插件。以下是一个简单的示例,展示如何进行正向和反向地理编码:
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:fl_geocoder/fl_geocoder.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Flutter Geocoding Example'),
),
body: GeocodingExample(),
),
);
}
}
class GeocodingExample extends StatefulWidget {
@override
_GeocodingExampleState createState() => _GeocodingExampleState();
}
class _GeocodingExampleState extends State<GeocodingExample> {
String _address = '';
String _latitude = '';
String _longitude = '';
Future<void> _getCurrentLocation() async {
bool serviceEnabled;
LocationPermission permission;
// Test if location services are enabled.
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
return Future.error('Location services are disabled.');
}
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
return Future.error('Location permissions are denied');
}
}
if (permission == LocationPermission.deniedForever) {
// Permissions are permanently denied, we cannot request permissions anymore.
return Future.error(
'Location permissions are permanently denied, we cannot request permissions.');
}
// Get the current position.
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high);
setState(() {
_latitude = position.latitude.toString();
_longitude = position.longitude.toString();
});
// Perform reverse geocoding.
List<Placemark> placemarks = await placemarkFromCoordinates(
position.latitude, position.longitude);
Placemark place = placemarks.isNotEmpty ? placemarks.first : null;
if (place != null) {
setState(() {
_address = "${place.thoroughfare}, ${place.locality}, ${place.postalCode}, ${place.country}";
});
}
}
Future<void> _getFromAddress() async {
String searchAddress = '1600 Amphitheatre Parkway, Mountain View, CA';
List<Placemark> placemarks = await placemarkFromAddress(searchAddress);
if (placemarks.isNotEmpty) {
Placemark place = placemarks.first;
setState(() {
_latitude = place.position.latitude.toString();
_longitude = place.position.longitude.toString();
});
}
}
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('Current Address:', style: TextStyle(fontSize: 18)),
Text(_address, style: TextStyle(fontSize: 16)),
SizedBox(height: 20),
Text('Current Coordinates:', style: TextStyle(fontSize: 18)),
Row(
children: <Widget>[
Text('Latitude: $_latitude'),
SizedBox(width: 20),
Text('Longitude: $_longitude'),
],
),
SizedBox(height: 40),
ElevatedButton(
onPressed: _getCurrentLocation,
child: Text('Get Current Location'),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: _getFromAddress,
child: Text('Get Coordinates from Address'),
),
],
),
);
}
}
解释
- 依赖导入:首先导入必要的包,包括
flutter
,geolocator
, 和fl_geocoder
。 - 权限检查:在获取位置之前,检查位置服务是否启用以及应用是否有权限访问位置信息。
- 获取当前位置:使用
Geolocator.getCurrentPosition()
获取当前设备的经纬度。 - 反向地理编码:使用
placemarkFromCoordinates()
将经纬度转换为地址。 - 正向地理编码:使用
placemarkFromAddress()
将地址转换为经纬度。 - UI展示:使用简单的UI组件展示地址和经纬度信息,并提供按钮触发上述功能。
注意:由于插件和API可能会随时间更新,请查阅最新的官方文档以获取最新的使用方法和最佳实践。