📅  最后修改于: 2021-01-05 08:51:46             🧑  作者: Mango
在上一教程中,我们构建了定位“地图固定位置”和“地图当前位置”的应用程序。
在本教程中,我们将在Google Map中实现搜索位置功能。 Google位置的搜索是通过Geocoder类完成的。 Geocoder类有助于地理编码和反向地理编码。
地理编码是将街道地址转换为坐标(纬度,经度)的过程。反向地理编码是将坐标(纬度,经度)转换为街道地址的过程。
在activity_maps.xml布局文件中添加以下代码。 EditText用于输入搜索位置,而Button用于单击事件以搜索位置。
在build.gradle文件中添加Google Map Service和Google Location Service依赖项。
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.google.android.gms:play-services-maps:11.8.0'
compile 'com.google.android.gms:play-services-location:11.8.0'
testImplementation 'junit:junit:4.12'
testImplementation 'junit:junit:4.12'
}
Kotlin Google Search Location
Google Search Location
将Google Map API密钥放置在res / values / google_map_api.xml文件中。
AIzaSyCKvLn2KTPKD_-REPLACE-WITH-YOUR-API
在MapsActivity.kt类文件中添加以下代码。
package example.javatpoint.com.kotlingooglesearchlocation
import android.os.Bundle
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
import android.location.Address
import android.location.Geocoder
import android.os.Build
import android.support.v4.app.FragmentActivity
import com.google.android.gms.common.api.GoogleApiClient
import com.google.android.gms.maps.model.BitmapDescriptorFactory
import com.google.android.gms.maps.model.Marker
import com.google.android.gms.location.LocationServices
import android.location.Location
import android.Manifest
import android.content.pm.PackageManager
import android.support.v4.content.ContextCompat
import android.view.View
import android.widget.EditText
import android.widget.Toast
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.location.LocationListener
import com.google.android.gms.location.LocationRequest
import java.io.IOException
class MapsActivity() : FragmentActivity(), OnMapReadyCallback, LocationListener,
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private var mMap: GoogleMap? = null
internal lateinit var mLastLocation: Location
internal var mCurrLocationMarker: Marker? = null
internal var mGoogleApiClient: GoogleApiClient? = null
internal lateinit var mLocationRequest: LocationRequest
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_maps)
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
val mapFragment = supportFragmentManager
.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
}
override fun onMapReady(googleMap: GoogleMap) {
mMap = googleMap
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient()
mMap!!.isMyLocationEnabled = true
}
} else {
buildGoogleApiClient()
mMap!!.isMyLocationEnabled = true
}
}
@Synchronized
protected fun buildGoogleApiClient() {
mGoogleApiClient = GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build()
mGoogleApiClient!!.connect()
}
override fun onConnected(bundle: Bundle?) {
mLocationRequest = LocationRequest()
mLocationRequest.interval = 1000
mLocationRequest.fastestInterval = 1000
mLocationRequest.priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
LocationServices.getFusedLocationProviderClient(this)
}
}
override fun onConnectionSuspended(i: Int) {
}
override fun onLocationChanged(location: Location) {
mLastLocation = location
if (mCurrLocationMarker != null) {
mCurrLocationMarker!!.remove()
}
//Place current location marker
val latLng = LatLng(location.latitude, location.longitude)
val markerOptions = MarkerOptions()
markerOptions.position(latLng)
markerOptions.title("Current Position")
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
mCurrLocationMarker = mMap!!.addMarker(markerOptions)
//move map camera
mMap!!.moveCamera(CameraUpdateFactory.newLatLng(latLng))
mMap!!.animateCamera(CameraUpdateFactory.zoomTo(11f))
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.getFusedLocationProviderClient(this)
}
}
override fun onConnectionFailed(connectionResult: ConnectionResult) {
}
fun searchLocation(view: View) {
val locationSearch:EditText = findViewById(R.id.editText)
lateinit var location: String
location = locationSearch.text.toString()
var addressList: List? = null
if (location == null || location == "") {
Toast.makeText(applicationContext,"provide location",Toast.LENGTH_SHORT).show()
}
else{
val geoCoder = Geocoder(this)
try {
addressList = geoCoder.getFromLocationName(location, 1)
} catch (e: IOException) {
e.printStackTrace()
}
val address = addressList!![0]
val latLng = LatLng(address.latitude, address.longitude)
mMap!!.addMarker(MarkerOptions().position(latLng).title(location))
mMap!!.animateCamera(CameraUpdateFactory.newLatLng(latLng))
Toast.makeText(applicationContext, address.latitude.toString() + " " + address.longitude, Toast.LENGTH_LONG).show()
}
}
}
输出:
注意:请在实际的Android设备上进行检查,以获取最佳输出结果。