📅  最后修改于: 2023-12-03 15:32:29.535000             🧑  作者: Mango
在 Android 应用中实现地图功能是十分常见的需求。谷歌提供了 Google Maps API 供 Android 开发者使用,简单方便,具有很高的可定制性。本文将介绍如何使用 Kotlin 和 Google Maps API 在 Android 应用中实现搜索位置功能。
首先,我们需要在项目中添加依赖:Google Maps Android API 和 Places API。
dependencies {
implementation 'com.google.android.gms:play-services-maps:17.0.0'
implementation 'com.google.android.gms:play-services-places:17.0.0'
}
我们需要添加以下权限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
接下来,我们需要获取 Google API 密钥。我们可以在 开发者控制台 中创建一个项目,然后在项目中启用 Google Maps Android API 和 Places API。创建完成后,我们可以在“凭据”页面中获取 API 密钥。
在开始之前,我们需要在布局文件中添加一个 SupportMapFragment
。
<fragment
android:id="@+id/mapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.SupportMapFragment"/>
接下来,我们需要在 Kotlin 代码中获取该 Fragment 并获取 GoogleMap
对象。
private lateinit var googleMap: GoogleMap
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mapFragment.getMapAsync { map ->
googleMap = map
}
}
接下来,我们需要实现搜索位置功能。我们可以使用 AutocompleteSupportFragment
进行搜索,它提供了自动完成和建议搜索结果。
private fun initSearch() {
val autocompleteFragment = childFragmentManager.findFragmentById(R.id.autocompleteFragment)
as AutocompleteSupportFragment
autocompleteFragment.setPlaceFields(listOf(Place.Field.ID, Place.Field.NAME, Place.Field.LAT_LNG))
autocompleteFragment.setOnPlaceSelectedListener(object : PlaceSelectionListener {
override fun onPlaceSelected(place: Place) {
googleMap.clear()
googleMap.addMarker(MarkerOptions().position(place.latLng).title(place.name))
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(place.latLng, 15F))
}
override fun onError(status: Status) {}
})
}
这里我们设定了 PlaceFields
为 ID、名称和经纬度,然后我们在 onPlaceSelected
方法中获取选择的位置并在地图上添加标记。
搜索位置需要访问设备的位置信息,我们需要请求相应的权限。
private fun requestPermissions() {
if (ActivityCompat.checkSelfPermission(requireContext(),
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(requireActivity(),
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), REQUEST_LOCATION_PERMISSION)
} else {
enableMyLocation()
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
if (requestCode == REQUEST_LOCATION_PERMISSION && grantResults.isNotEmpty()) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
enableMyLocation()
}
}
}
private fun enableMyLocation() {
if (ActivityCompat.checkSelfPermission(
requireContext(),
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED) {
return
}
googleMap.isMyLocationEnabled = true
}
class MapsFragment : Fragment() {
private val REQUEST_LOCATION_PERMISSION = 1
private lateinit var googleMap: GoogleMap
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_maps, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mapFragment.getMapAsync { map ->
googleMap = map
requestPermissions()
initSearch()
}
}
private fun requestPermissions() {
if (ActivityCompat.checkSelfPermission(requireContext(),
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(requireActivity(),
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), REQUEST_LOCATION_PERMISSION)
} else {
enableMyLocation()
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
if (requestCode == REQUEST_LOCATION_PERMISSION && grantResults.isNotEmpty()) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
enableMyLocation()
}
}
}
private fun enableMyLocation() {
if (ActivityCompat.checkSelfPermission(
requireContext(),
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED) {
return
}
googleMap.isMyLocationEnabled = true
}
private fun initSearch() {
val autocompleteFragment = childFragmentManager.findFragmentById(R.id.autocompleteFragment)
as AutocompleteSupportFragment
autocompleteFragment.setPlaceFields(listOf(Place.Field.ID, Place.Field.NAME, Place.Field.LAT_LNG))
autocompleteFragment.setOnPlaceSelectedListener(object : PlaceSelectionListener {
override fun onPlaceSelected(place: Place) {
googleMap.clear()
googleMap.addMarker(MarkerOptions().position(place.latLng).title(place.name))
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(place.latLng, 15F))
}
override fun onError(status: Status) {}
})
}
}
本文介绍了如何使用 Kotlin 和 Google Maps API 在 Android 应用中实现搜索位置功能。如果您想要学习更多关于 Google Maps API 的内容,请访问 官方文档。