Flutter projesi oluşturun

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.

  1. "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!
    . Uygulama kodunuz 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 uygulama iOS, Android ve Web'i hedefler. Google Haritalar SDK'sı şu anda tarayıcı dışındaki masaüstü uygulamalarını desteklememektedir.
  2. 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.

  1. android/app/build.gradle yapılandırma dosyasını tercih ettiğiniz IDE'de açın.
  2. android.defaultConfig.minSdkVersion değerini 21 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
        }
        //...
      }
  3. defaultConfig uygulamasını yapılandırırken kendi benzersiz ApplicationID'nizi belirtin.
  4. Dosyayı kaydedin ve projedeki değişikliklerinizi Gradle ile senkronize edin.

iOS

Minimum iOS platformu sürümünü belirleyin.

  1. ios/Podfile yapılandırma dosyasını tercih ettiğiniz IDE'de açın.
  2. 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:

  1. Android Studio'da üst düzey build.gradle veya build.gradle.kts dosyasını seçin ve aşağıdaki kodu altındaki dependencies öğesine ekleyin buildscript.

    Modern

    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")
        }
    }
    
  2. Modül düzeyindeki build.gradle dosyanızı açın ve aşağıdaki kodu plugins öğesi.

    Modern

    plugins {
        // ...
        id 'com.google.android.libraries.mapsplatform.secrets-gradle-plugin'
    }

    Kotlin

    plugins {
        id("com.google.android.libraries.mapsplatform.secrets-gradle-plugin")
    }
  3. Modül düzeyindeki build.gradle dosyanızda targetSdk ve compileSdk, 34 olarak ayarlandı.
  4. Dosyayı kaydedin ve projenizi Gradle ile senkronize edin.
  5. 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
  6. Dosyayı kaydedin.
  7. Ü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 bir secrets.properties dosyası oluşturmadınız API anahtarı.

  8. Dosyayı kaydedin.
  9. AndroidManifest.xml dosyanızda şuna gidin: com.google.android.geo.API_KEY ve android: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 name com.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.

  10. In Android Studio, open your module-level build.gradle or build.gradle.kts file and edit the secrets property. If the secrets property does not exist, add it.

    Edit the properties of the plugin to set propertiesFileName to secrets.properties, set defaultPropertiesFileName to local.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.*"
}
        

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ıca com.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.

  1. ios/Runner/AppDelegate.swift dosyasını Flutter projenizde, tercih ettiğiniz IDE ile açın.
  2. Flutter için Google Haritalar paketini uygulamanıza eklemek istiyorsanız şu içe aktarma ifadesini ekleyin:
  3. import GoogleMaps
  4. YOUR_API_KEY yerine API anahtarınızı girerek API'nizi application(_:didFinishLaunchingWithOptions:) yönteminize ekleyin:
    GMSServices.provideAPIKey("YOUR_API_KEY")
  5. AppDelegate.swift dosyasını kaydedip kapatın.

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.

  1. web/index.html dosyasını Flutter projenizde, tercih ettiğiniz IDE ile açın.
  2. Aşağıdaki komut dosyası etiketini <head> etiketinin içine ekleyerek YOUR_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>
    
  3. index.html dosyasını kaydedip kapatın.

    index.html dokümanının tam head 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.

  1. lib/main.dart dosyasını Flutter projenizde, tercih ettiğiniz IDE ile açın.
  2. 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,
                    ),
                  ),
                ),
              );
            }
          }
  3. Uygulamanızı çalıştırmak istediğiniz emülatörleri veya cihazları başlatın.
  4. 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: