ตั้งค่าโครงการ Flutter

ก่อนตั้งค่าโปรเจ็กต์ Flutter โปรดตรวจสอบให้แน่ใจว่าคุณได้ทำตามขั้นตอนเบื้องต้นในส่วนก่อนเริ่มต้นแล้ว หลังจากเปิดใช้การเรียกเก็บเงินและสร้างคีย์ API แล้ว คุณสามารถสร้างโปรเจ็กต์ Flutter ที่ใช้ในการพัฒนาแอปได้

ขั้นตอนที่ 1: ติดตั้งซอฟต์แวร์ที่จำเป็น

หากต้องการสร้างโปรเจ็กต์โดยใช้แพ็กเกจ Google Maps สำหรับ Flutter คุณต้องติดตั้ง Flutter SDK และตั้งค่าสภาพแวดล้อมการพัฒนาสำหรับแพลตฟอร์มเป้าหมาย ดูรายละเอียดได้ในคู่มือการติดตั้ง Flutter

ขั้นตอนที่ 2: ติดตั้งแพ็กเกจ Google Maps สำหรับ Flutter ในโปรเจ็กต์ใหม่

Flutter มีแพ็กเกจ Google Maps สำหรับ Flutter เป็นปลั๊กอิน Flutter

สร้างโปรเจ็กต์ Flutter และเพิ่มปลั๊กอิน Maps

  1. สร้างโปรเจ็กต์ Flutter ใหม่โดยใช้ "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 หากต้องการเรียกใช้แอปพลิเคชัน ให้พิมพ์ดังนี้
      cd google_maps_in_flutter
      flutter run
    แอปพลิเคชันนี้กําหนดเป้าหมายเป็น iOS, Android และเว็บ ในขณะนี้ Google Maps SDK ไม่สนับสนุนแอปพลิเคชันบนเดสก์ท็อปที่อยู่นอกเบราว์เซอร์
  2. เพิ่มปลั๊กอินแพ็กเกจ Google Maps for Flutter ลงในโปรเจ็กต์นี้
    flutter pub add google_maps_flutter
      
      Resolving dependencies...
      [Listing of dependencies elided]
    
      Changed 14 dependencies!

ขั้นตอนที่ 3: ตั้งค่าเวอร์ชันของแพลตฟอร์ม

Android

ตั้งค่าเวอร์ชัน SDK ขั้นต่ำสําหรับ Android

  1. เปิดไฟล์กำหนดค่า android/app/build.gradle ใน IDE ที่ต้องการ
  2. เปลี่ยนค่าของ android.defaultConfig.minSdkVersion เป็น 21:
      android {
        //...
        defaultConfig {
            applicationId "com.example.google_maps_in_flutter"
            minSdkVersion 21     // Set to 21
            targetSdkVersion flutter.targetSdkVersion
            versionCode flutterVersionCode.toInteger()
            versionName flutterVersionName
        }
        //...
      }
  3. เมื่อกำหนดค่า defaultConfig ให้ระบุ ApplicationID ที่ไม่ซ้ำกันของคุณเอง
  4. บันทึกไฟล์และซิงค์การเปลี่ยนแปลงโปรเจ็กต์กับ Gradle

iOS

ตั้งค่าเวอร์ชันแพลตฟอร์ม iOS ขั้นต่ำ

  1. เปิดไฟล์กำหนดค่า ios/Podfile ใน IDE ที่ต้องการ
  2. เพิ่มบรรทัดต่อไปนี้ที่จุดเริ่มต้นของ Podfile นี้
      # Set platform to 14.0 to enable latest Google Maps SDK
      platform :ios, '14.0'

ขั้นตอนที่ 4: เพิ่มคีย์ API ลงในโปรเจ็กต์

ในก่อนเริ่มต้น คุณได้สร้างคีย์ API สำหรับแอปแล้ว ต่อไปให้เพิ่มคีย์ดังกล่าวในโปรเจ็กต์ Flutter สำหรับ Flutter คุณควรเพิ่มคีย์ API นี้ลงในแพลตฟอร์มเป้าหมายทั้งหมด ได้แก่ iOS, Android และเว็บ

ในตัวอย่างต่อไปนี้ ให้แทนที่ YOUR_API_KEY ด้วยคีย์ API ของคุณ

Android

เราขอแนะนำให้ใช้ปลั๊กอิน Secrets Gradle สำหรับ Android เพื่อปรับปรุงงานนี้

วิธีติดตั้งปลั๊กอิน Secrets Gradle สำหรับ Android ในโปรเจ็กต์ Google Maps มีดังนี้

  1. ใน Android Studio ให้เปิดไฟล์ build.gradle หรือ build.gradle.kts ระดับบนสุด แล้วเพิ่มโค้ดต่อไปนี้ลงในองค์ประกอบ dependencies ในส่วน buildscript

    ดึงดูด

    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. เปิดไฟล์ build.gradle ระดับโมดูล และเพิ่มโค้ดต่อไปนี้ลงในองค์ประกอบ plugins

    ดึงดูด

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

    Kotlin

    plugins {
        id("com.google.android.libraries.mapsplatform.secrets-gradle-plugin")
    }
  3. ในไฟล์ build.gradle ระดับโมดูล ให้ตรวจสอบว่า targetSdk และ compileSdk ตั้งค่าเป็น 34
  4. บันทึกไฟล์และซิงค์โปรเจ็กต์กับ Gradle
  5. เปิดไฟล์ secrets.properties ในไดเรกทอรีระดับบนสุด แล้วเพิ่มโค้ดต่อไปนี้ แทนที่ YOUR_API_KEY ด้วยคีย์ API ของคุณ เก็บคีย์ของคุณไว้ในไฟล์นี้เนื่องจาก secrets.properties ได้รับการยกเว้นจากการตรวจสอบในระบบควบคุมเวอร์ชัน
    MAPS_API_KEY=YOUR_API_KEY
  6. บันทึกไฟล์
  7. สร้างไฟล์ local.defaults.properties ในไดเรกทอรีระดับบนสุดโดยใช้โฟลเดอร์เดียวกับไฟล์ secrets.properties แล้วเพิ่มโค้ดต่อไปนี้

    MAPS_API_KEY=DEFAULT_API_KEY

    วัตถุประสงค์ของไฟล์นี้คือการระบุตำแหน่งข้อมูลสำรองสำหรับคีย์ API หากไม่พบไฟล์ secrets.properties เพื่อให้บิลด์ทำงานไม่สำเร็จ กรณีนี้อาจเกิดขึ้นหากคุณโคลนแอปจากระบบควบคุมเวอร์ชันซึ่งละเว้น secrets.properties และยังไม่ได้สร้างไฟล์ secrets.properties ในเครื่องเพื่อระบุคีย์ API

  8. บันทึกไฟล์
  9. ในไฟล์ AndroidManifest.xml ให้ไปที่ com.google.android.geo.API_KEY และอัปเดต android:value attribute หากไม่มีแท็ก <meta-data> ให้สร้างเป็นแท็กย่อยของแท็ก <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 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.*"
}
        

หมายเหตุ: ดังที่แสดงด้านบน com.google.android.geo.API_KEY คือชื่อข้อมูลเมตาที่แนะนำสำหรับคีย์ API คีย์ที่มีชื่อนี้ใช้เพื่อตรวจสอบสิทธิ์ API หลายรายการใน Google Maps บนแพลตฟอร์ม Android ได้ ซึ่งรวมถึง Flutter SDK สำหรับความเข้ากันได้แบบย้อนหลัง API ยังรองรับชื่อ com.google.android.maps.v2.API_KEY ด้วย ชื่อเดิมนี้อนุญาตให้ตรวจสอบสิทธิ์ Android Maps API v2 เท่านั้น แอปพลิเคชันจะระบุชื่อข้อมูลเมตาคีย์ API ได้เพียงชื่อเดียวเท่านั้น หากระบุไว้ทั้ง 2 อย่าง API จะแสดงข้อยกเว้น

iOS

เพิ่มคีย์ API ลงในไฟล์ AppDelegate.swift

  1. เปิดไฟล์ ios/Runner/AppDelegate.swift ในโปรเจ็กต์ Flutter ด้วย IDE ที่ต้องการ
  2. เพิ่มคำสั่งการนำเข้าต่อไปนี้เพื่อเพิ่มแพ็กเกจ Google Maps สำหรับ Flutter ลงในแอปของคุณ
  3. import GoogleMaps
  4. เพิ่ม API ลงในเมธอด application(_:didFinishLaunchingWithOptions:) โดยแทนที่คีย์ API ของคุณสำหรับ YOUR_API_KEY:
    GMSServices.provideAPIKey("YOUR_API_KEY")
  5. บันทึกและปิดไฟล์ AppDelegate.swift

ไฟล์ AppDelegate.swift ที่เสร็จสมบูรณ์แล้วควรมีลักษณะดังนี้

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)
  }
}

เว็บไซต์

เพิ่มคีย์ API ไปยังไฟล์แอปพลิเคชัน index.html

  1. เปิดไฟล์ web/index.html ในโปรเจ็กต์ Flutter ด้วย IDE ที่ต้องการ
  2. เพิ่มแท็กสคริปต์ต่อไปนี้ในแท็ก <head> โดยแทนที่คีย์ API ของคุณสำหรับ YOUR_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>
    
  3. บันทึกและปิดไฟล์ index.html

    ส่วน head ที่สมบูรณ์ของ index.html ควรมีลักษณะดังนี้

        <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: เพิ่มแผนที่

โค้ดต่อไปนี้แสดงวิธีเพิ่มแผนที่แบบง่ายๆ ลงในแอป Flutter ใหม่

  1. เปิดไฟล์ lib/main.dart ในโปรเจ็กต์ Flutter ด้วย IDE ที่ต้องการ
  2. เพิ่มหรืออัปเดตเมธอดในเมธอดหลักที่เป็นค่าเริ่มต้นของแอปเพื่อสร้างและเริ่มต้นอินสแตนซ์ของ 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,
                    ),
                  ),
                ),
              );
            }
          }
  3. เริ่มโปรแกรมจำลองหรืออุปกรณ์ที่คุณต้องการให้เรียกใช้แอปพลิเคชัน
  4. เรียกใช้แอปพลิเคชันของคุณ คุณควรเห็นเอาต์พุตในลักษณะนี้
      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"): 

    พิมพ์หมายเลขของแพลตฟอร์มที่ต้องการเรียกใช้ ทุกครั้งที่คุณเรียกใช้ flutter run Flutter จะแสดงตัวเลือกเหล่านี้ให้คุณ หากระบบการพัฒนาของคุณไม่มีโปรแกรมจำลองที่ทำงานหรือเชื่อมต่ออุปกรณ์ทดสอบ Flutter ควรเลือกเปิด Chrome

    แต่ละแพลตฟอร์มควรแสดงแผนที่เป็นศูนย์กลางของซิดนีย์ ออสเตรเลีย หากไม่เห็นแผนที่ ให้ตรวจสอบว่าคุณได้เพิ่มคีย์ API ลงในโปรเจ็กต์เป้าหมายที่เหมาะสมแล้ว

ขั้นตอนถัดไป

เมื่อมีคีย์ API และโปรเจ็กต์ Flutter แล้ว คุณก็สร้างและเรียกใช้แอปได้ แพ็กเกจ Google Maps สำหรับ Flutter มีบทแนะนำและแอปตัวอย่างมากมายที่จะช่วยคุณเริ่มต้นใช้งาน ดูข้อมูลเพิ่มเติมได้ในแหล่งข้อมูลต่อไปนี้