Trước khi thiết lập một dự án Flutter, hãy đảm bảo bạn đã hoàn tất các bước tiên quyết trong phần Trước khi bắt đầu. Sau khi bật tính năng thanh toán và tạo khoá API, bạn có thể thiết lập dự án Flutter mà bạn dùng để phát triển ứng dụng.
Bước 1: Cài đặt phần mềm cần thiết
Để xây dựng một dự án bằng gói Google Maps dành cho Flutter, bạn phải cài đặt SDK Flutter và thiết lập môi trường phát triển cho nền tảng mục tiêu. Hãy xem Hướng dẫn cài đặt Flutter để biết thông tin chi tiết.
Bước 2: Cài đặt gói Google Maps dành cho Flutter trong một dự án mới
Flutter cung cấp gói Google Maps dành cho Flutter dưới dạng một trình bổ trợ Flutter.
Tạo dự án Flutter rồi thêm trình bổ trợ Maps.
-
Tạo một dự án Flutter mới bằng tính năng "flutter create" ("tạo flutter create"):
flutter create google_maps_in_flutter --platforms=android,ios,web
Creating project google_maps_in_flutter... [Listing of created files elided] Wrote 127 files. All done!google_maps_in_flutter/lib/main.dart
. Để chạy ứng dụng, hãy nhập:cd google_maps_in_flutter
flutter run
-
Thêm trình bổ trợ gói Google Maps dành cho Flutter vào dự án này.
flutter pub add google_maps_flutter
Resolving dependencies... [Listing of dependencies elided] Changed 14 dependencies!
Bước 3: Đặt phiên bản nền tảng
Android
Thiết lập phiên bản SDK tối thiểu cho Android.
- Mở tệp cấu hình
android/app/build.gradle
trong IDE ưa thích của bạn. - Thay đổi giá trị của
android.defaultConfig.minSdkVersion
thành21
:android { //... defaultConfig { applicationId "com.example.google_maps_in_flutter" minSdkVersion 21 // Set to 21 targetSdkVersion flutter.targetSdkVersion versionCode flutterVersionCode.toInteger() versionName flutterVersionName } //... }
- Khi định cấu hình
defaultConfig
, hãy chỉ định ApplicationID duy nhất của riêng bạn. - Lưu tệp và đồng bộ hoá các thay đổi của dự án với Gradle.
iOS
Đặt phiên bản nền tảng iOS tối thiểu.
- Mở tệp cấu hình
ios/Podfile
trong IDE ưa thích của bạn. - Thêm các dòng sau vào đầu Podfile này:
# Set platform to 14.0 to enable latest Google Maps SDK platform :ios, '14.0'
Bước 4: Thêm khoá API vào dự án
Trong phần Trước khi bắt đầu, bạn đã tạo một khoá API cho ứng dụng của mình. Bây giờ, hãy thêm khoá đó vào dự án Flutter. Đối với Flutter, bạn nên thêm khoá API này vào tất cả các nền tảng đích: iOS, Android và Web.
Trong các ví dụ sau, hãy thay thế YOUR_API_KEY
bằng khoá API.
Android
Để đơn giản hoá tác vụ này, bạn nên sử dụng Trình bổ trợ Bí mật cho Gradle cho Android.
Cách cài đặt Trình bổ trợ Secrets Gradle cho Android trong dự án Google Maps:
-
Trong Android Studio, hãy mở tệp
build.gradle
hoặcbuild.gradle.kts
cấp cao nhất rồi thêm mã sau vào phần tửdependencies
trongbuildscript
.Groovy
buildscript { dependencies { classpath "com.google.android.libraries.mapsplatform.secrets-gradle-plugin:secrets-gradle-plugin:2.0.1" } }
Kotlin
buildscript { dependencies { classpath("com.google.android.libraries.mapsplatform.secrets-gradle-plugin:secrets-gradle-plugin:2.0.1") } }
-
Mở tệp
build.gradle
ở cấp mô-đun và thêm mã sau vào phần tửplugins
.Groovy
plugins { // ... id 'com.google.android.libraries.mapsplatform.secrets-gradle-plugin' }
Kotlin
plugins { id("com.google.android.libraries.mapsplatform.secrets-gradle-plugin") }
- Trong tệp
build.gradle
ở cấp mô-đun, hãy đảm bảo rằngtargetSdk
vàcompileSdk
được đặt thành 34. - Lưu tệp và đồng bộ hoá dự án của bạn với Gradle.
-
Mở tệp
secrets.properties
trong thư mục cấp cao nhất của bạn, sau đó thêm mã sau. Thay thếYOUR_API_KEY
bằng khoá API. Lưu trữ khoá của bạn trong tệp này vìsecrets.properties
không được phép kiểm tra trong một hệ thống quản lý phiên bản.MAPS_API_KEY=YOUR_API_KEY
- Lưu tệp.
-
Tạo tệp
local.defaults.properties
trong thư mục cấp cao nhất, cùng thư mục với tệpsecrets.properties
, sau đó thêm mã sau.MAPS_API_KEY=DEFAULT_API_KEY
Mục đích của tệp này là cung cấp vị trí sao lưu cho khoá API nếu không tìm thấy tệp
secrets.properties
để các bản dựng không bị lỗi. Điều này có thể xảy ra nếu bạn sao chép ứng dụng từ một hệ thống quản lý phiên bản, trong đó bỏ quasecrets.properties
và bạn chưa tạo tệpsecrets.properties
cục bộ để cung cấp khoá API của mình. - Lưu tệp.
-
Trong tệp
AndroidManifest.xml
, hãy chuyển đếncom.google.android.geo.API_KEY
rồi cập nhậtandroid:value attribute
. Nếu thẻ<meta-data>
không tồn tại, hãy tạo thẻ này làm thẻ con của thẻ<application>
.<meta-data android:name="com.google.android.geo.API_KEY" android:value="${MAPS_API_KEY}" />
Note:
com.google.android.geo.API_KEY
is the recommended metadata name for the API key. A key with this name can be used to authenticate to multiple Google Maps-based APIs on the Android platform, including the Flutter SDK. For backwards compatibility, the API also supports the namecom.google.android.maps.v2.API_KEY
. This legacy name allows authentication to the Android Maps API v2 only. An application can specify only one of the API key metadata names. If both are specified, the API throws an exception. -
In Android Studio, open your module-level
build.gradle
orbuild.gradle.kts
file and edit thesecrets
property. If thesecrets
property does not exist, add it.Edit the properties of the plugin to set
propertiesFileName
tosecrets.properties
, setdefaultPropertiesFileName
tolocal.defaults.properties
, and set any other properties.Groovy
secrets { // Optionally specify a different file name containing your secrets. // The plugin defaults to "local.properties" propertiesFileName = "secrets.properties" // A properties file containing default secret values. This file can be // checked in version control. defaultPropertiesFileName = "local.defaults.properties" // Configure which keys should be ignored by the plugin by providing regular expressions. // "sdk.dir" is ignored by default. ignoreList.add("keyToIgnore") // Ignore the key "keyToIgnore" ignoreList.add("sdk.*") // Ignore all keys matching the regexp "sdk.*" }
Kotlin
secrets { // Optionally specify a different file name containing your secrets. // The plugin defaults to "local.properties" propertiesFileName = "secrets.properties" // A properties file containing default secret values. This file can be // checked in version control. defaultPropertiesFileName = "local.defaults.properties" // Configure which keys should be ignored by the plugin by providing regular expressions. // "sdk.dir" is ignored by default. ignoreList.add("keyToIgnore") // Ignore the key "keyToIgnore" ignoreList.add("sdk.*") // Ignore all keys matching the regexp "sdk.*" }
Lưu ý: Như đã trình bày ở trên,
com.google.android.geo.API_KEY
là tên siêu dữ liệu nên dùng cho khoá API. Khoá có tên này có thể dùng để xác thực nhiều API dựa trên Google Maps trên nền tảng Android, bao gồm cả SDK Flutter. Để có khả năng tương thích ngược, API cũng hỗ trợ têncom.google.android.maps.v2.API_KEY
. Tên cũ này chỉ cho phép xác thực với API Android Maps phiên bản 2. Một ứng dụng chỉ có thể chỉ định một trong các tên siêu dữ liệu của khoá API. Nếu bạn chỉ định cả hai, thì API sẽ gửi ra một ngoại lệ.iOS
Thêm khoá API vào tệp
AppDelegate.swift
.- Mở tệp
ios/Runner/AppDelegate.swift
trong dự án Flutter bằng IDE mà bạn muốn. - Thêm câu lệnh nhập sau để thêm gói Google Maps dành cho Flutter vào ứng dụng của bạn:
- Thêm API vào phương thức
application(_:didFinishLaunchingWithOptions:)
, thay thế khoá API bằng YOUR_API_KEY:GMSServices.provideAPIKey("YOUR_API_KEY")
- Lưu rồi đóng tệp
AppDelegate.swift
.
import GoogleMaps
Tệp
AppDelegate.swift
hoàn chỉnh sẽ có dạng như sau:import UIKit import Flutter import GoogleMaps // Add this import @UIApplicationMain @objc class AppDelegate: FlutterAppDelegate { override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { GeneratedPluginRegistrant.register(with: self) // TODO: Add your Google Maps API key GMSServices.provideAPIKey("YOUR_API_KEY") return super.application(application, didFinishLaunchingWithOptions: launchOptions) } }
Web
Thêm khoá API vào tệp ứng dụng
index.html
.- Mở tệp
web/index.html
trong dự án Flutter bằng IDE mà bạn muốn. - Thêm thẻ tập lệnh sau đây vào thẻ
<head>
, thay thế khoá API bằngYOUR_API_KEY
.<script> (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({ key: "YOUR_API_KEY", v: "weekly", // Use the 'v' parameter to indicate the version to use (weekly, beta, alpha, etc.). // Add other bootstrap parameters as needed, using camel case. }); </script>
- Lưu rồi đóng tệp
index.html
.Phần
head
hoàn chỉnh củaindex.html
sẽ có dạng như sau:<head> <base href="/"> <meta charset="UTF-8"> <meta content="IE=Edge" http-equiv="X-UA-Compatible"> <meta name="description" content="A new Flutter project."> <!-- iOS meta tags & icons --> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <meta name="apple-mobile-web-app-title" content="google_maps_in_flutter"> <link rel="apple-touch-icon" href="icons/Icon-192.png"> <script> (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({ key: "YOUR_API_KEY", v: "weekly", // Use the 'v' parameter to indicate the version to use (weekly, beta, alpha, etc.). // Add other bootstrap parameters as needed, using camel case. }); </script> <title>google_maps_in_flutter</title> <link rel="manifest" href="manifest.json"> </head>
Bước 5: Thêm bản đồ
Mã sau đây minh hoạ cách thêm một bản đồ đơn giản vào một ứng dụng Flutter mới.
- Mở tệp
lib/main.dart
trong dự án Flutter bằng IDE mà bạn muốn. - Thêm hoặc cập nhật các phương thức trong phương thức chính mặc định của ứng dụng để tạo và khởi chạy một thực thể của
mapController
.import 'package:flutter/material.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; void main() => runApp(const MyApp()); class MyApp extends StatefulWidget { const MyApp({super.key}); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { late GoogleMapController mapController; final LatLng _center = const LatLng(-33.86, 151.20); void _onMapCreated(GoogleMapController controller) { mapController = controller; } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('Maps Sample App'), backgroundColor: Colors.green[700], ), body: GoogleMap( onMapCreated: _onMapCreated, initialCameraPosition: CameraPosition( target: _center, zoom: 11.0, ), ), ), ); } }
- Khởi động trình mô phỏng hoặc thiết bị bất kỳ mà bạn muốn chạy ứng dụng.
- Chạy ứng dụng. Bạn sẽ thấy kết quả tương tự như sau:
flutter run
Multiple devices found: Android phone (mobile) • emulator-5554 • android-arm64 • Android 13 (API 33) (emulator) iPhone (mobile) • ios • com.apple.CoreSimulator.SimRuntime.iOS-16-2 (simulator) Chrome (web) • chrome • web-javascript • Google Chrome 108.0.5359.124 [1]: Android phone [2]: iPhone [3]: Chrome Please choose one (To quit, press "q/Q"):Nhập số nền tảng bạn muốn chạy. Mỗi lần bạn gọi
flutter run
, Flutter sẽ hiển thị cho bạn các lựa chọn này. Nếu hệ thống phát triển của bạn không có trình mô phỏng đang chạy hoặc thiết bị thử nghiệm được kết nối, Flutter nên chọn mở Chrome.Mỗi nền tảng phải hiển thị một bản đồ ở trung tâm Sydney, Úc. Nếu không thấy bản đồ, hãy kiểm tra để chắc chắn rằng bạn đã thêm khoá API vào dự án mục tiêu phù hợp.
Các bước tiếp theo
Giờ đây, khi đã có khoá API và một dự án Flutter, bạn có thể tạo và chạy các ứng dụng. Gói Google Maps dành cho Flutter cung cấp nhiều hướng dẫn và ứng dụng mẫu có thể giúp bạn bắt đầu. Để tìm hiểu thêm, hãy xem các tài nguyên sau:
- Hướng dẫn Thêm bản đồ bằng điểm đánh dấu
- Lớp học lập trình về Flutter với Nền tảng Google Maps
- Mã mẫu trên GitHub
- Mở tệp
Trừ khi có lưu ý khác, nội dung của trang này được cấp phép theo Giấy phép ghi nhận tác giả 4.0 của Creative Commons và các mẫu mã lập trình được cấp phép theo Giấy phép Apache 2.0. Để biết thông tin chi tiết, vui lòng tham khảo Chính sách trang web của Google Developers. Java là nhãn hiệu đã đăng ký của Oracle và/hoặc các đơn vị liên kết với Oracle.
Cập nhật lần gần đây nhất: 2024-05-03 UTC.