Flutter路线规划插件flutter_polyline_points的使用
Flutter路线规划插件flutter_polyline_points的使用
flutter_polyline_points
flutter_polyline_points
是一个Flutter插件,它可以将Google编码的polyline字符串解码为适合在地图上显示路线/多段线的地理坐标列表。
开始使用
这个包包含了函数用于解码Google编码的polyline字符串,返回一个表示两个地理位置之间路径的坐标列表。
添加依赖
要使用此包,请按照官方文档中的说明,在pubspec.yaml
文件中添加flutter_polyline_points
作为依赖项。
dependencies:
flutter_polyline_points: ^latest_version # 替换为最新版本号
导入包
在Dart文件中导入包:
import 'package:flutter_polyline_points/flutter_polyline_points.dart';
使用方法
方法一:通过地理坐标获取点列表
该方法根据地理坐标返回PolylineResult
实例,其中包含API状态、错误信息以及解码后的点列表。
PolylinePoints polylinePoints = PolylinePoints();
PolylineResult result = await polylinePoints.getRouteBetweenCoordinates(
googleApiKey: "YOUR_GOOGLE_API_KEY",
request: PolylineRequest(
origin: PointLatLng(_originLatitude, _originLongitude),
destination: PointLatLng(_destLatitude, _destLongitude),
mode: TravelMode.driving,
wayPoints: [PolylineWayPoint(location: "Sabo, Yaba Lagos Nigeria")],
),
);
print(result.points);
方法二:解码编码的polyline字符串
直接解码给定的Google polyline字符串。
List<PointLatLng> result = polylinePoints.decodePolyline("_p~iF~ps|U_ulLnnqC_mqNvxq`@");
print(result);
方法三:获取带有替代路线的polyline
此方法返回多个PolylineResult
,每个代表一条可能的路线。
List<PolylineResult> results = await PolylinePoints().getRouteBetweenCoordinates(
googleApiKey: "YOUR_GOOGLE_API_KEY",
request: PolylineRequest(
origin: PointLatLng(_originLatitude, _originLongitude),
destination: PointLatLng(_destLatitude, _destLongitude),
mode: TravelMode.driving,
wayPoints: [PolylineWayPoint(location: "Sabo, Yaba Lagos Nigeria")],
),
);
print(results.length);
提示
请确保使用有效的Google API密钥。如果需要帮助生成API密钥,请访问官方文档。
完整示例代码
下面是一个完整的示例应用程序,它展示了如何在地图上绘制路线。
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:flutter_polyline_points/flutter_polyline_points.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Polyline example',
theme: ThemeData(
primarySwatch: Colors.orange,
),
home: MapScreen(),
);
}
}
class MapScreen extends StatefulWidget {
@override
_MapScreenState createState() => _MapScreenState();
}
class _MapScreenState extends State<MapScreen> {
late GoogleMapController mapController;
double _originLatitude = 6.5212402, _originLongitude = 3.3679965;
double _destLatitude = 6.849660, _destLongitude = 3.648190;
Map<MarkerId, Marker> markers = {};
Map<PolylineId, Polyline> polylines = {};
List<LatLng> polylineCoordinates = [];
PolylinePoints polylinePoints = PolylinePoints();
String googleAPiKey = "YOUR_GOOGLE_API_KEY";
@override
void initState() {
super.initState();
// 添加起点标记
_addMarker(LatLng(_originLatitude, _originLongitude), "origin", BitmapDescriptor.defaultMarker);
// 添加终点标记
_addMarker(LatLng(_destLatitude, _destLongitude), "destination", BitmapDescriptor.defaultMarkerWithHue(90));
_getPolyline();
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: GoogleMap(
initialCameraPosition: CameraPosition(
target: LatLng(_originLatitude, _originLongitude),
zoom: 15,
),
myLocationEnabled: true,
tiltGesturesEnabled: true,
compassEnabled: true,
scrollGesturesEnabled: true,
zoomGesturesEnabled: true,
onMapCreated: _onMapCreated,
markers: Set<Marker>.of(markers.values),
polylines: Set<Polyline>.of(polylines.values),
),
),
);
}
void _onMapCreated(GoogleMapController controller) async {
mapController = controller;
}
void _addMarker(LatLng position, String id, BitmapDescriptor descriptor) {
MarkerId markerId = MarkerId(id);
Marker marker = Marker(markerId: markerId, icon: descriptor, position: position);
markers[markerId] = marker;
}
void _addPolyLine() {
PolylineId id = PolylineId("poly");
Polyline polyline = Polyline(polylineId: id, color: Colors.red, points: polylineCoordinates);
polylines[id] = polyline;
setState(() {});
}
Future<void> _getPolyline() async {
PolylineResult result = await polylinePoints.getRouteBetweenCoordinates(
googleApiKey: googleAPiKey,
request: PolylineRequest(
origin: PointLatLng(_originLatitude, _originLongitude),
destination: PointLatLng(_destLatitude, _destLongitude),
mode: TravelMode.driving,
wayPoints: [PolylineWayPoint(location: "Sabo, Yaba Lagos Nigeria")],
),
);
if (result.points.isNotEmpty) {
result.points.forEach((PointLatLng point) {
polylineCoordinates.add(LatLng(point.latitude, point.longitude));
});
}
_addPolyLine();
}
}
以上代码创建了一个简单的Flutter应用,该应用在地图上显示了从起点到终点的路线,并且可以在地图上看到起点和终点的标记。请确保替换YOUR_GOOGLE_API_KEY
为您自己的Google API密钥。
更多关于Flutter路线规划插件flutter_polyline_points的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter路线规划插件flutter_polyline_points的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,下面是一个使用 flutter_polyline_points
插件在 Flutter 中实现路线规划的示例代码。这个插件通常用于在地图上绘制两点之间的路线,并生成所需的经纬度点。
首先,确保你已经在 pubspec.yaml
文件中添加了 flutter_polyline_points
和 google_maps_flutter
依赖:
dependencies:
flutter:
sdk: flutter
google_maps_flutter: ^2.1.1
flutter_polyline_points: ^1.0.0
然后,运行 flutter pub get
来获取这些依赖。
接下来,在你的 Flutter 应用中实现路线规划功能。以下是一个完整的示例代码:
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:flutter_polyline_points/flutter_polyline_points.dart';
import 'package:geocoder/geocoder.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MapScreen(),
);
}
}
class MapScreen extends StatefulWidget {
@override
_MapScreenState createState() => _MapScreenState();
}
class _MapScreenState extends State<MapScreen> {
GoogleMapController? _mapController;
LatLng? _destination;
LatLng? _origin;
List<LatLng> polylineCoordinates = [];
PolylinePoints polylinePoints = PolylinePoints();
Polyline? polyline;
@override
void initState() {
super.initState();
_getCurrentLocation();
}
Future<void> _getCurrentLocation() async {
// 这里可以使用 Geolocator 或其他定位插件来获取当前位置
// 为了简化示例,我们直接设置一些固定的经纬度
setState(() {
_origin = LatLng(37.7749, -122.4194); // 旧金山
_destination = LatLng(34.0522, -118.2437); // 洛杉矶
});
_getPolylinePoints();
}
Future<void> _getPolylinePoints() async {
var polylineOptions = PolylineOptions(
points: polylineCoordinates,
color: Colors.blue,
width: 4,
joinType: PolylineJoinType.round,
endCapType: PolylineEndCapType.round,
startCapType: PolylineEndCapType.round,
);
if (_origin != null && _destination != null) {
List<PointLatLng> points = await polylinePoints.getRouteBetweenCoordinates(
GoogleMapsApiKey.YOUR_GOOGLE_MAPS_API_KEY, // 替换为你的 Google Maps API Key
_origin!.latitude,
_origin!.longitude,
_destination!.latitude,
_destination!.longitude
);
polylineCoordinates = points.map((PointLatLng point) => LatLng(point.latitude, point.longitude)).toList();
if (mounted) {
setState(() {
polyline = Polyline.fromPolylineOptions(polylineOptions);
});
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Polyline Points Example'),
),
body: GoogleMap(
mapType: MapType.normal,
initialCameraPosition: CameraPosition(
target: _origin ?? LatLng(0, 0),
zoom: 10.0,
),
onMapCreated: (GoogleMapController controller) {
_mapController = controller;
if (polyline != null) {
_mapController?.addPolyline(polyline!);
}
},
markers: {
MarkerOptions(
position: _origin ?? LatLng(0, 0),
icon: BitmapDescriptor.defaultMarker,
),
MarkerOptions(
position: _destination ?? LatLng(0, 0),
icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueAzure),
),
}.values.toList(),
),
);
}
}
class GoogleMapsApiKey {
static const String YOUR_GOOGLE_MAPS_API_KEY = 'YOUR_ACTUAL_API_KEY'; // 替换为实际的 Google Maps API Key
}
说明:
- 依赖:确保你已经添加了
google_maps_flutter
和flutter_polyline_points
依赖。 - API Key:将
YOUR_GOOGLE_MAPS_API_KEY
替换为你的实际 Google Maps API Key。 - 定位:为了简化示例,我们直接设置了固定的起点和终点。在实际应用中,你可能需要使用
geolocator
或其他定位插件来获取当前位置。 - 路线计算:使用
flutter_polyline_points
插件的getRouteBetweenCoordinates
方法来获取两点之间的路线,并将其绘制在地图上。
这个示例展示了如何使用 flutter_polyline_points
插件在 Flutter 中实现基本的路线规划功能。你可以根据需要进一步扩展和自定义这个示例。