Flutter projesi oluşturmadan önce, gerekli önkoşulu yerine getirdiğinizden emin olun: Başlamadan önce bölümündeki adımları uygulayın. Etkinleştirdikten sonra faturalandırma bir API anahtarı oluşturduktan sonra, Google Etiket Yöneticisi'nde kullandığınız Flutter projesini yardımcı olabilir.
1. Adım: Gerekli yazılımı yükleyin
Flutter için Google Haritalar paketini kullanarak bir proje oluşturmak istiyorsanız Google Maps for Flutter paketini kullanarak Flutter SDK'sını tıklayın ve hedef platformunuz için geliştirme ortamınızı kurun. Daha fazla bilgi için Flutter yüklemesi rehberini inceleyin.
2. Adım: Flutter için Google Haritalar paketini yeni bir projede yükleyin
Flutter, Flutter eklentisi olarak Flutter için Google Haritalar paketini sunar.
Flutter projesini oluşturun ve Haritalar eklentisini ekleyin.
-
"Flutter create" komutunu kullanarak yeni bir Flutter projesi oluşturun:
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
dilinde. Uygulamanızı çalıştırmak için şunu yazın:cd google_maps_in_flutter
flutter run
-
Bu projeye Google Maps for Flutter paket eklentisini ekleyin.
flutter pub add google_maps_flutter
Resolving dependencies... [Listing of dependencies elided] Changed 14 dependencies!
3. Adım: Platform sürümünü ayarlayın
Android
Android için minimum SDK sürümünü belirleyin.
android/app/build.gradle
yapılandırma dosyasını tercih ettiğiniz IDE'de açın.android.defaultConfig.minSdkVersion
değerini21
olarak değiştirin:android { //... defaultConfig { applicationId "com.example.google_maps_in_flutter" minSdkVersion 21 // Set to 21 targetSdkVersion flutter.targetSdkVersion versionCode flutterVersionCode.toInteger() versionName flutterVersionName } //... }
defaultConfig
uygulamasını yapılandırırken kendi benzersiz ApplicationID'nizi belirtin.- Dosyayı kaydedin ve projedeki değişikliklerinizi Gradle ile senkronize edin.
iOS
Minimum iOS platformu sürümünü belirleyin.
ios/Podfile
yapılandırma dosyasını tercih ettiğiniz IDE'de açın.- Bu Podfile'ın başına aşağıdaki satırları ekleyin:
# Set platform to 14.0 to enable latest Google Maps SDK platform :ios, '14.0'
.
4. Adım: API anahtarınızı projeye ekleyin
Başlamadan önce bölümünde uygulamanız için bir API anahtarı oluşturdunuz. Şimdi ekleyin çok önemli bir parçasıdır. Flutter için bu API anahtarını tüm hedef platformlar: iOS, Android ve Web.
Aşağıdaki örneklerde YOUR_API_KEY
öğesini kendi API anahtarınızla değiştirin.
Android
Bu görevi kolaylaştırmak için Android için Secrets Gradle Plugin.
Google Haritalar projenize Android için Secrets Gradle Eklentisi'ni yüklemek için:
-
Android Studio'da üst düzey
build.gradle.kts
veyabuild.gradle
öğenizi açın dosyasını seçin ve aşağıdaki kodu altındakidependencies
öğesine ekleyinbuildscript
.Kotlin
buildscript { dependencies { classpath("com.google.android.libraries.mapsplatform.secrets-gradle-plugin:secrets-gradle-plugin:2.0.1") } }
Modern
buildscript { dependencies { classpath "com.google.android.libraries.mapsplatform.secrets-gradle-plugin:secrets-gradle-plugin:2.0.1" } }
-
Modül düzeyindeki
build.gradle.kts
veyabuild.gradle
dosyanızı açın veplugins
öğesine aşağıdaki kodu ekleyin.Kotlin
plugins { // ... id("com.google.android.libraries.mapsplatform.secrets-gradle-plugin") }
Modern
plugins { // ... id 'com.google.android.libraries.mapsplatform.secrets-gradle-plugin' }
- Modül düzeyindeki
build.gradle.kts
veyabuild.gradle
dosyanızdatargetSdk
vecompileSdk
ayarlandığı için 34 yaşa. - Dosyayı kaydedin ve projenizi Gradle ile senkronize edin.
-
secrets.properties
dosyasını en üst düzey dizininizde açın ve şunu ekleyin: aşağıdaki kodu kullanabilirsiniz.YOUR_API_KEY
kısmını API anahtarınızla değiştirin. Anahtarınızı bu dosyada depolayın çünküsecrets.properties
, sürüm kontrolüne kontrol edilmekten hariç tutuldu bahsedeceğim.MAPS_API_KEY=YOUR_API_KEY
- Dosyayı kaydedin.
-
Üst düzey dizininizde
local.defaults.properties
dosyasını oluşturun. klasörünüsecrets.properties
dosyası olarak kaydedin, ardından aşağıdaki kodu ekleyin.MAPS_API_KEY=DEFAULT_API_KEY
Bu dosyanın amacı, Derlemelerin başarısız olmaması için
secrets.properties
dosyası bulunamadı. Bu durum, uygulamayı,secrets.properties
ve sağlamak için henüz yerel olarak birsecrets.properties
dosyası oluşturmadınız API anahtarı. - Dosyayı kaydedin.
-
AndroidManifest.xml
dosyanızda şuna gidin:com.google.android.geo.API_KEY
veandroid:value attribute
öğesini güncelleyin.<meta-data>
etiketi mevcut değilse bunu<application>
etiketi.<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.kts
orbuild.gradle
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.Kotlin
secrets { // To add your Maps API key to this project: // 1. If the secrets.properties file does not exist, create it in the same folder as the local.properties file. // 2. Add this line, where YOUR_API_KEY is your API key: // MAPS_API_KEY=YOUR_API_KEY 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.*" }
Modern
secrets { // To add your Maps API key to this project: // 1. If the secrets.properties file does not exist, create it in the same folder as the local.properties file. // 2. Add this line, where YOUR_API_KEY is your API key: // MAPS_API_KEY=YOUR_API_KEY 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.*" }
Not: Yukarıda gösterildiği gibi,
com.google.android.geo.API_KEY
önerilen meta veri adıdır girin. Bu ada sahip bir anahtar, birden fazla kimlik doğrulamasında kullanılabilir Android platformundaki Google Haritalar tabanlı Google Haritalar tabanlı API'ler: Flutter SDK'sı. Geriye dönük uyumluluk için API ayrıcacom.google.android.maps.v2.API_KEY
adını destekler. Bu eski name yalnızca Android Maps API v2 ile kimlik doğrulamasına izin verir. Bir uygulama API anahtarı meta veri adlarından yalnızca birini belirtme. Her ikisi de belirtilmişse API bir istisna oluşturur.iOS
API anahtarınızı
AppDelegate.swift
dosyanıza ekleyin.ios/Runner/AppDelegate.swift
dosyasını Flutter projenizde, tercih ettiğiniz IDE ile açın.- Flutter için Google Haritalar paketini uygulamanıza eklemek istiyorsanız şu içe aktarma ifadesini ekleyin:
- YOUR_API_KEY yerine API anahtarınızı girerek API'nizi
application(_:didFinishLaunchingWithOptions:)
yönteminize ekleyin:GMSServices.provideAPIKey("YOUR_API_KEY")
AppDelegate.swift
dosyasını kaydedip kapatın.
import GoogleMaps
Tamamlanan
AppDelegate.swift
dosyası aşağıdakine benzer şekilde görünecektir: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
API anahtarınızı
index.html
uygulama dosyanıza ekleyin.web/index.html
dosyasını Flutter projenizde, tercih ettiğiniz IDE ile açın.- Aşağıdaki komut dosyası etiketini
<head>
etiketinin içine ekleyerekYOUR_API_KEY
için API anahtarınızı değiştirin.<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>
index.html
dosyasını kaydedip kapatın.index.html
dokümanının tamhead
bölümü aşağıdakine benzer şekilde görünmelidir:<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>
5. Adım: Bir harita ekleyin
Aşağıdaki kod, yeni bir Flutter uygulamasına basit bir haritanın nasıl ekleneceğini gösterir.
lib/main.dart
dosyasını Flutter projenizde, tercih ettiğiniz IDE ile açın.mapController
örneği oluşturmak ve başlatmak için uygulamanızın varsayılan ana yönteminde yöntemler ekleyin veya güncelleyin.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, ), ), ), ); } }
- Uygulamanızı çalıştırmak istediğiniz emülatörleri veya cihazları başlatın.
- Uygulamanızı çalıştırın. Şuna benzer bir çıkış alırsınız:
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"):Çalıştırmak istediğiniz platformun numarasını yazın.
flutter run
öğesini her çağırdığınızda Flutter size bu seçenekleri sunar. Geliştirme sisteminizde çalışan veya bağlı bir test cihazı yoksa Flutter, Chrome'u açmayı seçmelidir.Her platform, Sidney, Avustralya merkezli bir harita görüntülemelidir. Haritayı görmediyseniz API anahtarınızı uygun hedef projeye ekleyip eklemediğinizi kontrol edin.
Sonraki adımlar
API anahtarınız ve Flutter projeniz olduğuna göre artık uygulama oluşturup çalıştırabilirsiniz. Flutter için Google Haritalar paketi, Google Maps for Flutter'ı kullanan size yardımcı olabilir. Daha fazla bilgi edinmek için aşağıdaki kaynaklara göz atın:
- İşaretçi İçeren Harita Ekleme eğiticisi
- Codelabs Google Haritalar Platformu ile Flutter için
- Kod örnekleri GitHub'da
Aksi belirtilmediği sürece bu sayfanın içeriği Creative Commons Atıf 4.0 Lisansı altında ve kod örnekleri Apache 2.0 Lisansı altında lisanslanmıştır. Ayrıntılı bilgi için Google Developers Site Politikaları'na göz atın. Java, Oracle ve/veya satış ortaklarının tescilli ticari markasıdır.
Son güncelleme tarihi: 2024-09-05 UTC.