Company insights

การใช้งาน Google Map ใน Flutter


การนำ Google Map มาใช้งานใน Flutter เป็นฟีเจอร์ที่นิยมใช้ในแอปที่เกี่ยวกับตำแหน่ง
เช่น แอปเรียกรถ แอปขนส่ง หรือแอปค้นหาสถานที่ใกล้ตัวผู้ใช้
Flutter สามารถเชื่อมต่อกับ Google Maps ผ่าน Plugin ที่ชื่อว่า
google_maps_flutter ซึ่งช่วยให้สามารถแสดงแผนที่
ปักหมุด (Marker) และจัดการตำแหน่งต่าง ๆ ได้อย่างสะดวก

ขั้นตอนการใช้งาน Google Map ใน Flutter

1. สร้างโปรเจกต์ Flutter


เริ่มต้นด้วยการสร้างโปรเจกต์ Flutter ใหม่ด้วยคำสั่ง


flutter create flutter_map_app


จากนั้นเข้าไปยังโฟลเดอร์โปรเจกต์


cd flutter_map_app

2. เพิ่ม Package Google Maps


เปิดไฟล์ pubspec.yaml แล้วเพิ่ม dependency


dependencies:
 flutter:
   sdk: flutter
 google_maps_flutter: ^2.5.0


จากนั้นรันคำสั่ง


flutter pub get

3. ขอ Google Maps API Key


การใช้งาน Google Maps จำเป็นต้องมี API Key โดยสามารถสร้างได้จาก
Google Cloud Console


  • ไปที่ Google Cloud Platform

  • สร้าง Project ใหม่

  • เปิดใช้งาน Maps SDK for Android หรือ iOS

  • สร้าง API Key

4. เพิ่ม API Key ใน Android


เปิดไฟล์
android/app/src/main/AndroidManifest.xml
แล้วเพิ่มโค้ดดังนี้


<meta-data
 android:name="com.google.android.geo.API_KEY"
 android:value="YOUR_API_KEY"/>

5. ตัวอย่างการแสดง Google Map ใน Flutter


ตัวอย่างโค้ดสำหรับแสดง Google Map บนหน้าจอ


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

class MapPage extends StatefulWidget {
 @override
 _MapPageState createState() => _MapPageState();
}

class _MapPageState extends State<MapPage> {

 static const LatLng _center = LatLng(13.7563, 100.5018);

 late GoogleMapController mapController;

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

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

6. การเพิ่ม Marker ลงในแผนที่


Marker คือจุดที่ใช้แสดงตำแหน่งบนแผนที่ เช่น ตำแหน่งร้านค้า
ตำแหน่งคนขับ หรือสถานที่สำคัญ


Set<Marker> markers = {
 Marker(
   markerId: MarkerId('bangkok'),
   position: LatLng(13.7563, 100.5018),
   infoWindow: InfoWindow(
     title: 'Bangkok',
     snippet: 'Thailand',
   ),
 ),
};


และเพิ่ม marker เข้าไปใน GoogleMap widget


GoogleMap(
 initialCameraPosition: CameraPosition(
   target: LatLng(13.7563, 100.5018),
   zoom: 12,
 ),
 markers: markers,
)

ตัวอย่างการใช้งานจริง


Google Maps ใน Flutter มักถูกใช้ในระบบต่าง ๆ เช่น


  • แอปเรียกรถ เช่น Grab หรือ Uber

  • แอปขนส่งสินค้า

  • แอปค้นหาร้านอาหารใกล้ตัว

  • ระบบติดตามตำแหน่งรถแบบ Real-time

สรุป


การใช้งาน Google Map ใน Flutter สามารถทำได้ง่ายผ่าน Plugin
google_maps_flutter โดยต้องมีการสร้าง API Key
จาก Google Cloud ก่อน จากนั้นจึงนำมาใส่ในโปรเจกต์ Flutter
และสามารถแสดงแผนที่ ปักหมุด Marker หรือพัฒนาฟีเจอร์
เกี่ยวกับตำแหน่งต่าง ๆ ได้ตามต้องการ