Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách dùng Location API trong Android để theo dõi vị trí hiện tại bằng Kotlin

Giới thiệu

Bài viết này minh họa cách sử dụng Location API trong Android để theo dõi vị trí hiện tại sử dụng Kotlin và Google Maps.

Các bước thực hiện

Bước 1: Tạo dự án mới

Mở Android Studio, chọn File → New Project và điền đầy đủ thông tin để tạo dự án mới.

Bước 2: Thiết kế giao diện (res/layout/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" />

Bước 3: Viết MapsActivity (src/MapsActivity.kt)

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
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

class MapsActivity : AppCompatActivity(), OnMapReadyCallback {
    private lateinit var mMap: GoogleMap

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_maps)
        
        val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
        mapFragment.getMapAsync(this)
    }

    override fun onMapReady(googleMap: GoogleMap) {
        mMap = googleMap
        val myCurrentLocation = LatLng(13.0827, 80.2707) // Chennai, India
        mMap.addMarker(MarkerOptions().position(myCurrentLocation).title("Đây là vị trí hiện tại của tôi"))
        mMap.moveCamera(CameraUpdateFactory.newLatLng(myCurrentLocation))
    }
}

Bước 4: Cấu hình Manifest (androidManifest.xml)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.q11">
    <uses-permission android:name="android.permission.ACCESS_FINE_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=".MainActivity">
            <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="YOUR_API_KEY_HERE" />
    </application>
</manifest>

Chạy ứng dụng

Kết nối thiết bị Android thực với máy tính. Trong Android Studio, mở file activity và nhấn biểu tượng Run trên thanh công cụ. Chọn thiết bị di động của bạn và kiểm tra màn hình hiển thị.

Lưu ý quan trọng: Ví dụ này dùng tọa độ cứng (hardcoded). Để lấy vị trí thực, cần FusedLocationProviderClient như bài 1003062103. Cần API Key Google Maps và bật Maps SDK cho Android trong Cloud Console.