google_maps_flutter_example
一个新的 Flutter 应用程序,演示如何在 Flutter 应用程序中实现 Flutter 谷歌地图并对其执行高级任务。
将地图添加到应用
-
在 https://cloud.google.com/maps-platform/ 获取 API 密钥。
-
为每个平台启用 Google Map SDK。
- 转到 Google Developers Console。
- 选择您要为其启用 Google Maps 的项目。
- 选择导航菜单,然后选择“Google Maps”。
- 在“Google Maps”菜单下选择“APIs”。
- 要为Android启用Google Maps,请在“Additional APIs”部分选择“Maps SDK for Android”,然后选择“ENABLE”。
- 要为iOS启用Google Maps,请在“Additional APIs”部分选择“Maps SDK for iOS”,然后选择“ENABLE”。
- 确保已启用的API位于“Enabled APIs”部分下。
-
在
android/app/src/main/AndroidManifest.xml文件中的Application标签内添加您的密钥。
<manifest ...
<application ...
<meta-data android:name="com.google.android.geo.API_KEY"
android:value="YOUR KEY HERE"/>
- 在
ios/Runner/AppDelegate.swift文件中添加以下行。
import UIKit
import Flutter
import GoogleMaps
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GMSServices.provideAPIKey("YOUR KEY HERE")
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
- 将
lib/widget文件夹中的GoogleMapsWidget.dart作为普通小部件使用,并在需要的地方使用它。
向地图添加自定义标记

添加普通标记
- 声明一个将在地图上显示的标记集。
Set<Marker> _markers = Set<Marker>();
- 将标记集添加到GoogleMap小部件。
GoogleMap(
markers: _markers,
- 在 onMapCreated 中更新标记集。
GoogleMap(
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
_setMapPins([LatLng(30.029585, 31.022356)]);
}
- 使用此函数,地图将在其上带有给定标记进行更新。
_setMapPins(List<LatLng> markersLocation) {
_markers.clear();
setState(() {
markersLocation.forEach((markerLocation) {
_markers.add(Marker(
markerId: MarkerId(markerLocation.toString()),
position: markerLocation,
));
});
});
}
自定义标记
- 声明一个将保存自定义图标的BitmapDescriptor。
late BitmapDescriptor customIcon;
- 在 initState() 中将所需的png分配给 customIcon。
@override
void initState() {
BitmapDescriptor.fromAssetImage(ImageConfiguration(size: Size(50, 50)),
'assets/images/marker_car.png')
.then((icon) {
customIcon = icon;
});
super.initState();
}
- 最后,将 customIcon 添加到标记。
Marker(
markerId: MarkerId(markerLocation.toString()),
position: markerLocation,
icon: customIcon,
)
地图自定义(浅色/深色模式)
准备地图样式。
- 转到 https://mapstyle.withgoogle.com/。
- 通过选择 No thanks, take me to the old style wizard 来选择旧版本的网站。
- 您会发现很多选项,随意调整,直到获得所需的样式。
- 单击“Finish”,将弹出您的样式json代码,将其复制并作为json文件添加到您的assets文件夹中。
别忘了在您的pubspec.yaml中提及它。
您可以在项目assets文件夹中找到两种样式。
为地图添加样式
- 声明将保存样式json的字符串,以及一个用于控制地图上显示哪种模式的布尔值。
bool mapDarkMode = true;
late String _darkMapStyle;
late String _lightMapStyle;
- 在initState中声明样式。
Future _loadMapStyles() async {
_darkMapStyle = await rootBundle.loadString('assets/map_style/dark.json');
_lightMapStyle = await rootBundle.loadString('assets/map_style/light.json');
}
- 创建地图后,设置样式。
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
_setMapPins([LatLng(30.029585, 31.022356)]);
_setMapStyle();
},
Future _setMapStyle() async {
final controller = await _controller.future;
if (mapDarkMode)
controller.setMapStyle(_darkMapStyle);
else
controller.setMapStyle(_lightMapStyle);
}
- 为了改变样式,我们使用stack小部件在地图上创建了一个按钮。
Positioned(
top: 100,
right: 30,
child: Container(
height: 30,
width: 30,
child: IconButton(
icon: Icon(
mapDarkMode ? Icons.brightness_4 : Icons.brightness_5,
color: Theme.of(context).primaryColor,
),
onPressed: () {
setState(() {
mapDarkMode = !mapDarkMode;
_setMapStyle();
});
},
),
)),
绘制路线
激活Directions API
- 转到 Google Developers Console。
- 选择您要为其启用 Google Maps 的项目。
- 选择导航菜单,然后选择“Google Maps”。
- 在“Google Maps”菜单下选择“APIs”。
- 启用Google Directions,在“Additional APIs”部分选择“Directions API”,然后选择“ENABLE”。
- 确保已启用的API位于“Enabled APIs”部分下。
向地图添加路线
- 声明您的起点和终点。
final LatLng initialLatLng = LatLng(30.029585, 31.022356);
final LatLng destinationLatLng = LatLng(30.060567, 30.962413);
- 声明polyline和polylineCoordinates。
Set<Polyline> _polyline = {};
List<LatLng> polylineCoordinates = [];
- 创建地图后,设置polyline。
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
_setMapPins([LatLng(30.029585, 31.022356)]);
_setMapStyle();
_addPolyLines();
},
_addPolyLines() {
setState(() {
lat = (initialLatLng.latitude + destinationLatLng.latitude)/2;
lng= (initialLatLng.longitude + destinationLatLng.longitude)/2;
_moveCamera(13.0);
_setPolyLines();
});
}
- 为了设置polyline,我们向 https://www.maps.googleapis.com/maps/api/directions/json 发送一个get请求,其中包含起始位置、结束位置和API密钥。
final result = await MapRepository()
.getRouteCoordinates(initialLatLng, destinationLatLng);
final route = result.data["routes"][0]["overview_polyline"]["points"];
- 然后,我们使用MapUtils将结果转换为polyline。
_polyline.add(Polyline(
polylineId: PolylineId("tripRoute"),
//pass any string here
width: 3,
geodesic: true,
points: MapUtils.convertToLatLng(MapUtils.decodePoly(route)),
color: Theme.of(context).primaryColor));
GitHub
https://github.com/heshamerfan97/flutter_google_maps_example