Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีตรวจจับการแตะและตำแหน่งบน Google Maps ใน Android

ภาพรวม

ตัวอย่างนี้สาธิตวิธีการตรวจจับการเคลื่อนย้ายแผนที่ (Camera Movement) และแยกประเภทสาเหตุ: จesture ผู้ใช้, API Animation, หรือ Developer Animation

ขั้นตอนที่ 1: สร้างโปรเจกต์ Google Maps

ใน Android Studio ไปที่ File → New Project → Google Maps Activity แล้วกรอกข้อมูล

ขั้นตอนที่ 2: จัดรูปแบบหน้าจอ (activity_maps.xml)

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MapsActivity" />

ขั้นตอนที่ 3: เขียนโค้ดหลัก (MapsActivity.java)

package com.example.googlemapstouch;

import android.os.Bundle;
import android.widget.Toast;
import androidx.fragment.app.FragmentActivity;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements
        OnMapReadyCallback,
        GoogleMap.OnCameraMoveStartedListener,
        GoogleMap.OnCameraMoveListener,
        GoogleMap.OnCameraMoveCanceledListener,
        GoogleMap.OnCameraIdleListener {
    
    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        
        // เพิ่ม Marker ที่ Sydney
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
        
        // ลงทะเบียน Listener ทั้ง 4 ตัว
        mMap.setOnCameraIdleListener(this);
        mMap.setOnCameraMoveStartedListener(this);
        mMap.setOnCameraMoveListener(this);
        mMap.setOnCameraMoveCanceledListener(this);
    }

    @Override
    public void onCameraMoveStarted(int reason) {
        String message;
        switch (reason) {
            case GoogleMap.OnCameraMoveStartedListener.REASON_GESTURE:
                message = "ผู้ใช้ทำ Gesture บนแผนที่ (ลาก/ซูม)";
                break;
            case GoogleMap.OnCameraMoveStartedListener.REASON_API_ANIMATION:
                message = "ผู้ใช้แตะที่ Marker หรือ UI ของแผนที่";
                break;
            case GoogleMap.OnCameraMoveStartedListener.REASON_DEVELOPER_ANIMATION:
                message = "แอปย้ายกล้องผ่านโค้ด (animateCamera)";
                break;
            default:
                message = "สาเหตุไม่ทราบ";
        }
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onCameraMove() {
        Toast.makeText(this, "กล้องกำลังเคลื่อนที่...", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onCameraMoveCanceled() {
        Toast.makeText(this, "การเคลื่อนที่ของกล้องถูกยกเลิก", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onCameraIdle() {
        // กล้องหยุดเคลื่อนที่ - เหมาะสำหรับดึงตำแหน่งปัจจุบัน
        LatLng center = mMap.getCameraPosition().target;
        Toast.makeText(this, "กล้องหยุดที่: " + center.latitude + ", " + center.longitude, Toast.LENGTH_SHORT).show();
    }
}

ขั้นตอนที่ 4: เพิ่ม API Key (google_maps_api.xml)

<resources>
    <string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">YOUR_MAP_KEY</string>
</resources>

ขั้นตอนที่ 5: ตั้งค่า Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.googlemapstouch">
    
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        
        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />
            
    </application>
</manifest>

การทดสอบ

รันแอปพลิเคชันบนอุปกรณ์จริง (ต้องมี Google Play Services) ลองลากแผนที่ แตะ Marker ซูมเข้า-ออก จะเห็น Toast แสดงสาเหตุ

วิธีตรวจจับการแตะและตำแหน่งบน Google Maps ใน Android

การได้ตำแหน่งที่แตะจริง (OnMapClickListener)

หากต้องการตำแหน่งพิกัดที่ผู้ใช้แตะโดยตรง ให้ใช้:

mMap.setOnMapClickListener(latLng -> {
    // latLng คือตำแหน่งที่ผู้ใช้แตะ
    Toast.makeText(this, "Tapped at: " + latLng.latitude + ", " + latLng.longitude, Toast.LENGTH_SHORT).show();
});

mMap.setOnMapLongClickListener(latLng -> {
    // Long press
});