问题描述
我正在尝试在 google 地图上的两点之间添加折线,但似乎不起作用。我按照 youtube https://youtu.be/CT6RkWL3GNE 和本网站 https://dev.to/olayemii/adding-route-paths-polylines-between-two-points-to-google-maps-in-flutter-23o2 上的教程编写代码。我使用 Flutter_polyline_points 包来创建折线。我不知道我的代码有什么问题。
这是我的代码。
const LatLng SOURCE_LOCATION = LatLng(13.652720,100.493635);
const LatLng DEST_LOCATION = LatLng(13.6640896,100.4357021);
class Direction extends StatefulWidget {
@override
_DirectionState createState() => _DirectionState();
}
class _DirectionState extends State<Direction> {
Completer<GoogleMapController> mapController = Completer();
Set<Marker> _markers = Set<Marker>();
LatLng currentLocation;
LatLng destinationLocation;
Set<polyline> _polylines = Set<polyline>();
List<LatLng> polylineCoordinates = [];
polylinePoints polylinePoints;
@override
void initState() {
super.initState();
polylinePoints = polylinePoints();
this.setinitialLocation();
}
void setinitialLocation() {
currentLocation =
LatLng(SOURCE_LOCATION.latitude,SOURCE_LOCATION.longitude);
destinationLocation =
LatLng(DEST_LOCATION.latitude,DEST_LOCATION.longitude);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Direction"),),body: GoogleMap(
myLocationEnabled: true,compassEnabled: false,tiltGesturesEnabled: false,polylines: _polylines,markers: _markers,onMapCreated: (GoogleMapController controller) {
mapController.complete(controller);
showMarker();
setpolylines();
},initialCameraPosition: CameraPosition(
target: SOURCE_LOCATION,zoom: 13,);
}
void showMarker() {
setState(() {
_markers.add(Marker(
markerId: MarkerId('sourcePin'),position: currentLocation,icon: BitmapDescriptor.defaultMarker,));
_markers.add(Marker(
markerId: MarkerId('destinationPin'),position: destinationLocation,icon: BitmapDescriptor.defaultMarkerWithHue(90),));
});
}
void setpolylines() async {
polylineResult result = await polylinePoints.getRouteBetweenCoordinates(
"<GOOGLE_MAPS_API_KEY_HERE>",PointLatLng(currentLocation.latitude,currentLocation.longitude),PointLatLng(
destinationLocation.latitude,destinationLocation.longitude));
if (result.status == 'OK') {
result.points.forEach((PointLatLng point) {
polylineCoordinates.add(LatLng(point.latitude,point.longitude));
});
setState(() {
_polylines.add(polyline(
width: 10,polylineId: polylineId('polyLine'),color: Color(0xFF08A5CB),points: polylineCoordinates));
});
}
}
}
解决方法
问题似乎出在您的 API 密钥上。我使用我自己的 API 密钥尝试了您的代码,并且能够显示折线(请参见下面的屏幕截图)。要使其在您的终端工作,请确保:
- 您正在使用有效的 API 密钥并且
- Directions API 在您的项目中启用并且
- 您的项目已关联到有效的结算帐号
请参阅此 documentation 以了解更多信息。