如何在 Android 上使用 Kotlin 在 Google 地图上显示当前位置?
此示例演示了如何使用 Kotlin 在 Android 上的 Google 地图上显示当前位置。
步骤 1 - 在 Android Studio 中创建一个新项目,转到文件 ⇒ 新建项目,并填写所有必需的详细信息以创建新项目。
步骤 2 - 将以下代码添加到 res/layout/activity_main.xml。
<fragment xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://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" />
步骤 3 - 在 build.gradle (Module: app) 中添加给定的依赖项
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'
步骤 4 - 将以下代码添加到 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() } } } }
步骤 5 - 要获取 google API 密钥 (map_key),请按照以下步骤操作
点击项目下拉菜单,选择或创建要为其添加 API 密钥的项目。
点击菜单按钮
并选择 API 和服务 > 凭据。
在“凭据”页面上,点击“创建凭据”>“API 密钥”。“已创建的 API 密钥”对话框会显示您新创建的 API 密钥。
点击关闭。
在清单文件中添加 API 密钥 <meta−data></meta−data>,如步骤 6 所示
步骤 6 - 将以下代码添加到 androidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://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>
让我们尝试运行您的应用程序。我假设您已将您的实际 Android 移动设备连接到您的计算机。要从 Android Studio 运行应用程序,请打开您项目中的一个活动文件,然后点击工具栏中的运行图标 。选择您的移动设备作为选项,然后检查您的移动设备,它将显示您的默认屏幕
广告