본문으로 건너뛰기

เนื้อหาภาษาไทย / 태국어 콘텐츠

시스템 가이드 검수 완료된 콘텐츠

การใช้ Google Maps API ใน Flutter

บทความนี้สอนวิธีการใช้งาน Google Maps API ใน Flutter โดยเริ่มต้นจากการตั้งค่า API Key บน Google Cloud Platform และการติดตั้ง package ที่จำเป็น จากนั้นอธิบายถึงก...

การใช้ Google Maps API ใน Flutter

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

สิ่งที่ต้องมีก่อนเริ่ม

  • Flutter SDK ติดตั้งและตั้งค่าเรียบร้อยแล้ว
  • Android Studio หรือ VS Code พร้อม Flutter extension
  • Google Cloud Platform account
  • Project Flutter ที่สร้างไว้แล้ว

ขั้นตอนการตั้งค่า Google Maps API

  1. เปิดใช้งาน Google Maps API: ไปที่ Google Cloud Console และสร้างโปรเจ็กต์ใหม่ หรือเลือกโปรเจ็กต์ที่มีอยู่ จากนั้นค้นหา "Maps SDK for Android" และ "Maps SDK for iOS" แล้วเปิดใช้งานทั้งสองอย่าง
  2. สร้าง API Key: ใน Google Cloud Console ไปที่ "Credentials" และสร้าง API Key โดยเลือก "API key (unrestricted)" (สำหรับเริ่มต้น) หรือจำกัดการใช้งานตามแพลตฟอร์ม (Android/iOS) เพื่อความปลอดภัย
  3. เพิ่ม Dependencies: เพิ่ม package `google_maps_flutter` ในไฟล์ `pubspec.yaml` ของโปรเจ็กต์ Flutter ของคุณ:
    dependencies:
      flutter:
        sdk: flutter
      google_maps_flutter: ^2.0.0 # หรือเวอร์ชันล่าสุด
    
    จากนั้นรัน `flutter pub get` ใน terminal
  4. ตั้งค่า API Key ใน Android:
    • เปิดไฟล์ `android/app/src/main/AndroidManifest.xml`
    • เพิ่ม metadata tag ภายใน `` tag:
      <meta-data
          android:name="com.google.android.geo.API_KEY"
          android:value="YOUR_API_KEY"/>
      
      แทนที่ `YOUR_API_KEY` ด้วย API key ที่คุณสร้างไว้
  5. ตั้งค่า API Key ใน iOS:
    • เปิดไฟล์ `ios/Runner/AppDelegate.swift` หรือ `ios/Runner/AppDelegate.m`
    • เพิ่มโค้ดต่อไปนี้ (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_API_KEY")
          GeneratedPluginRegistrant.register(with: self)
          return super.application(application, didFinishLaunchingWithOptions: launchOptions)
        }
      }
      
      หรือ (Objective-C):
      #import "AppDelegate.h"
      #import "GeneratedPluginRegistrant.h"
      #import <GoogleMaps/GoogleMaps.h>
      
      @implementation AppDelegate
      
      - (BOOL)application:(UIApplication *)application
          didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        [GMSServices provideAPIKey:@"YOUR_API_KEY"];
        [GeneratedPluginRegistrant registerWithRegistry:self];
        // Override point for customization after application launch.
        return [super application:application didFinishLaunchingWithOptions:launchOptions];
      }
      
      @end
      
      แทนที่ `YOUR_API_KEY` ด้วย API key ที่คุณสร้างไว้

การใช้งาน GoogleMap Widget

หลังจากตั้งค่า API Key เรียบร้อยแล้ว เราสามารถเริ่มใช้งาน `GoogleMap` widget ได้เลย

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

class MapScreen extends StatefulWidget {
  @override
  _MapScreenState createState() => _MapScreenState();
}

class _MapScreenState extends State<MapScreen> {
  GoogleMapController? mapController; //controller for Google map
  final LatLng _center = const LatLng(45.521563, -122.677433);

  void _onMapCreated(GoogleMapController controller) {
    mapController = controller;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Google Maps in Flutter'),
      ),
      body: GoogleMap(
        onMapCreated: _onMapCreated,
        initialCameraPosition: CameraPosition(
          target: _center,
          zoom: 11.0,
        ),
      ),
    );
  }
}

คำอธิบาย:

  • `GoogleMapController`: เป็นตัวควบคุมแผนที่ ช่วยให้เราสามารถจัดการแผนที่ได้ เช่น การเคลื่อนย้ายกล้อง, การเพิ่ม Markers เป็นต้น
  • `LatLng`: คลาสที่เก็บค่า latitude และ longitude ของตำแหน่งบนแผนที่
  • `CameraPosition`: กำหนดตำแหน่งเริ่มต้นและระดับการซูมของแผนที่
  • `onMapCreated`: ฟังก์ชันที่เรียกเมื่อแผนที่ถูกสร้างขึ้น เราจะใช้ฟังก์ชันนี้เพื่อเก็บ `GoogleMapController` ไว้
  • `initialCameraPosition`: กำหนดตำแหน่งเริ่มต้นของกล้องเมื่อแผนที่โหลด
  • `target`: ตำแหน่ง latitude และ longitude ที่กล้องจะโฟกัส
  • `zoom`: ระดับการซูมของแผนที่

การเพิ่ม Markers

Markers คือสัญลักษณ์ที่ใช้ปักหมุดตำแหน่งบนแผนที่ เราสามารถเพิ่ม Markers ได้โดยใช้ `Marker` class

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

class MapScreen extends StatefulWidget {
  @override
  _MapScreenState createState() => _MapScreenState();
}

class _MapScreenState extends State<MapScreen> {
  GoogleMapController? mapController; //controller for Google map
  final LatLng _center = const LatLng(45.521563, -122.677433);

  final Set<Marker> _markers = {};

  void _onMapCreated(GoogleMapController controller) {
    mapController = controller;
    setState(() {
      _markers.add(
        Marker(
          markerId: MarkerId('home'),
          position: _center,
          infoWindow: InfoWindow(
            title: 'My Home',
            snippet: 'This is my home location',
          ),
          icon: BitmapDescriptor.defaultMarker,
        ),
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Google Maps with Markers'),
      ),
      body: GoogleMap(
        onMapCreated: _onMapCreated,
        initialCameraPosition: CameraPosition(
          target: _center,
          zoom: 11.0,
        ),
        markers: _markers,
      ),
    );
  }
}

คำอธิบาย:

  • `MarkerId`: ID ที่ใช้ระบุ Marker แต่ละอัน
  • `position`: ตำแหน่ง latitude และ longitude ของ Marker
  • `infoWindow`: หน้าต่างที่แสดงข้อมูลเมื่อแตะที่ Marker
  • `title`: หัวข้อของ InfoWindow
  • `snippet`: รายละเอียดของ InfoWindow
  • `icon`: ไอคอนที่ใช้แสดง Marker
  • `markers`: Set ของ Marker ที่จะแสดงบนแผนที่

การวาด Polylines

Polylines คือเส้นที่เชื่อมต่อจุดหลายจุดบนแผนที่ เราสามารถวาด Polylines ได้โดยใช้ `Polyline` class

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

class MapScreen extends StatefulWidget {
  @override
  _MapScreenState createState() => _MapScreenState();
}

class _MapScreenState extends State<MapScreen> {
  GoogleMapController? mapController; //controller for Google map
  final LatLng _center = const LatLng(45.521563, -122.677433);

  final Set<Polyline> _polylines = {};

  void _onMapCreated(GoogleMapController controller) {
    mapController = controller;
    setState(() {
      _polylines.add(
        Polyline(
          polylineId: PolylineId('route'),
          points: [
            LatLng(45.521563, -122.677433),
            LatLng(45.531563, -122.687433),
            LatLng(45.541563, -122.697433),
          ],
          color: Colors.blue,
          width: 5,
        ),
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Google Maps with Polylines'),
      ),
      body: GoogleMap(
        onMapCreated: _onMapCreated,
        initialCameraPosition: CameraPosition(
          target: _center,
          zoom: 11.0,
        ),
        polylines: _polylines,
      ),
    );
  }
}

คำอธิบาย:

  • `PolylineId`: ID ที่ใช้ระบุ Polyline แต่ละอัน
  • `points`: รายการของ `LatLng` ที่กำหนดจุดบนเส้น
  • `color`: สีของเส้น
  • `width`: ความกว้างของเส้น
  • `polylines`: Set ของ Polyline ที่จะแสดงบนแผนที่

การควบคุมตำแหน่งของกล้อง

เราสามารถควบคุมตำแหน่งของกล้องได้โดยใช้ `GoogleMapController`

mapController?.animateCamera(
  CameraUpdate.newCameraPosition(
    CameraPosition(
      target: LatLng(45.551563, -122.707433),
      zoom: 15,
    ),
  ),
);

คำอธิบาย:

  • `animateCamera`: ฟังก์ชันที่ใช้เคลื่อนย้ายกล้องไปยังตำแหน่งใหม่
  • `CameraUpdate.newCameraPosition`: สร้าง CameraUpdate object ที่กำหนดตำแหน่งใหม่ของกล้อง

สรุป

ในบทเรียนนี้ เราได้เรียนรู้วิธีการใช้งาน Google Maps API ใน Flutter ตั้งแต่การตั้งค่า API Key, การใช้งาน `GoogleMap` widget, การเพิ่ม Markers, การวาด Polylines และการควบคุมตำแหน่งของกล้อง คุณสามารถนำความรู้เหล่านี้ไปประยุกต์ใช้ในการสร้างแอปพลิเคชันที่เกี่ยวข้องกับแผนที่ได้อย่างหลากหลาย ในบทเรียนต่อไป เราจะมาเรียนรู้วิธีการใช้งาน Camera API ใน Flutter

Office.in.th Custom Service

이 구조를 바탕으로 시스템을 개발하거나 맞춤 변경하고 싶으신가요?

Office.in.th는 엔터프라이즈 웹 애플리케이션, API 연동, 공공/민간 업무 관리 시스템을 설계·개발하며 장기 지원을 제공합니다.

소프트웨어 개발 서비스 보기