Computer >> Máy Tính >  >> Lập trình >> Android

Làm cách nào để hiển thị vị trí hiện tại trên Google Map trên Android bằng Kotlin?

Ví dụ này trình bày cách hiển thị vị trí hiện tại trên Bản đồ Google trên Android bằng Kotlin.

Bước 1 - Tạo một dự án mới trong Android Studio, đi tới Tệp ⇒ Dự án Mới và điền tất cả các chi tiết cần thiết để tạo một dự án mới.

Bước 2 - Thêm mã sau vào res / layout / activity_main.xml.

<fragment xmlns:android="https://schemas.android.com/apk/res/android"
   xmlns:tools="https://schemas.android.com/tools"
   android:id="@+id/myMap"
   android:name="com.google.android.gms.maps.SupportMapFragment"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity" />

Bước 3 - Thêm phụ thuộc đã cho trong build.gradle (Mô-đun:ứng dụng)

implementation 'com.google.android.gms:play-services-maps:17.0.0'
implementation 'com.google.android.gms:play-services-location:17.0.0'
implementation 'com.google.android.gms:play-services-maps:17.0.0'

Bước 4 - Thêm mã sau vào src / MainActivity.kt

import android.Manifest
import android.content.pm.PackageManager
import android.location.Location
import android.os.Bundle
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.fragment.app.FragmentActivity
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
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 MainActivity : FragmentActivity(), OnMapReadyCallback {
   private lateinit var currentLocation: Location
   private lateinit var fusedLocationProviderClient: FusedLocationProviderClient
   private val permissionCode = 101
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      fusedLocationProviderClient =  LocationServices.getFusedLocationProviderClient(this@MainActivity)
      fetchLocation()
   }
   private fun fetchLocation() {
      if (ActivityCompat.checkSelfPermission(
      this, Manifest.permission.ACCESS_FINE_LOCATION) !=
      PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
      this, Manifest.permission.ACCESS_COARSE_LOCATION) !=
      PackageManager.PERMISSION_GRANTED) {
         ActivityCompat.requestPermissions(this,
         arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), permissionCode)
         return
      }
      val task = fusedLocationProviderClient.lastLocation
      task.addOnSuccessListener { location −>
         if (location != null) {
            currentLocation = location
            Toast.makeText(applicationContext, currentLocation.latitude.toString() + "" +
            currentLocation.longitude, Toast.LENGTH_SHORT).show()
            val supportMapFragment = (supportFragmentManager.findFragmentById(R.id.myMap) as
            SupportMapFragment?)!!
            supportMapFragment.getMapAsync(this@MainActivity)
         }
      }
   }
   override fun onMapReady(googleMap: GoogleMap?) {
      val latLng = LatLng(currentLocation.latitude, currentLocation.longitude)
      val markerOptions = MarkerOptions().position(latLng).title("I am here!")
      googleMap?.animateCamera(CameraUpdateFactory.newLatLng(latLng))
      googleMap?.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 5f))
      googleMap?.addMarker(markerOptions)
   }
   override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String?>,
   grantResults: IntArray) {
      when (requestCode) {
         permissionCode −> if (grantResults.isNotEmpty() && grantResults[0] ==
         PackageManager.PERMISSION_GRANTED) {
            fetchLocation()
         }  
      }
   }
}

Bước 5 - Để lấy khóa API google (map_key), vui lòng làm theo các bước bên dưới

Truy cập Bảng điều khiển nền tảng đám mây của Google.

  • Nhấp vào trình đơn thả xuống dự án và chọn hoặc tạo dự án mà bạn muốn thêm khóa API.

  • Nhấp vào nút menu Làm cách nào để hiển thị vị trí hiện tại trên Google Map trên Android bằng Kotlin? và chọn API &dịch vụ> Thông tin đăng nhập.

  • Trên trang Thông tin xác thực, nhấp vào Tạo thông tin xác thực> Khóa API. Hộp thoại đã tạo khóa API hiển thị khóa API mới được tạo của bạn.

  • Nhấp vào Đóng.

  • Khóa API mới được liệt kê trên trang Thông tin đăng nhập trong khóa API. (Hãy nhớ hạn chế khóa API trước khi sử dụng trong sản xuất.)

  • Thêm khóa API vào tệp kê khai như được hiển thị trong bước 6

Bước 6 - Thêm mã sau vào androidManifest.xml

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

Hãy thử chạy ứng dụng của bạn. Tôi giả sử bạn đã kết nối thiết bị Di động Android thực tế với máy tính của mình. Để chạy ứng dụng từ android studio, hãy mở một trong các tệp hoạt động của dự án của bạn và nhấp vào biểu tượng Run Làm cách nào để hiển thị vị trí hiện tại trên Google Map trên Android bằng Kotlin? từ thanh công cụ. Chọn thiết bị di động của bạn làm tùy chọn, sau đó kiểm tra thiết bị di động sẽ hiển thị màn hình mặc định của bạn

Làm cách nào để hiển thị vị trí hiện tại trên Google Map trên Android bằng Kotlin?