我试图在谷歌地图上的两点之间添加折线,但它似乎不起作用。我按照 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 密钥尝试了您的代码,并且能够显示折线(请参见下面的屏幕截图)。为了使其在您端发挥作用,请确保:
请参阅此文档了解更多信息。
要使用 Directions API,您需要从 google 地图 API 控制台启用计费,否则,折线将不会出现/响应/显示!