Kotlin Android Google地图搜索位置

在上一教程中, 我们构建了定位地图固定位置和地图当前位置的应用程序。
在本教程中, 我们将在Google Map中实现搜索位置功能。 Google位置的搜索是通过Geocoder类完成的。 Geocoder类有助于地理编码和反向地理编码。
地理编码是将街道地址转换为坐标(纬度, 经度)的过程。反向地理编码是将坐标(纬度, 经度)转换为街道地址的过程。
Geocoder类的方法

  1. List getFromLocation(double latitude, double longitude, int maxResults):此方法返回一个Address数组, 该数组指定周围的纬度和经度。
  2. 列表getFromLocationName(String location, int results, double leftLatitude, double leftLongitude, double rightLatitude, double rightLongitude):此方法返回一个Address数组, 该数组描述了给定的位置, 例如位置, 地址等。
  3. List getFromLocationName(String location, int results):此方法返回一个Address数组, 该数组描述给定的位置, 例如位置, 地址等。
  4. static boolean isPresent():如果实现了方法getFromLocation()和getFromLocationName(), 则此方法返回true。
activity_maps.xml
将以下代码添加到activity_maps.xml布局文件中。 EditText用于输入搜索位置, 而Button用于单击事件以搜索位置。
< fragment xmlns:android="http://schemas.android.com/apk/res/android"xmlns:map="http://schemas.android.com/apk/res-auto"xmlns:tools="http://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="example.srcmini.com.kotlingooglesearchlocation.MapsActivity" > < LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"> < EditTextandroid:layout_width="248dp"android:layout_height="wrap_content"android:id="@+id/editText"android:layout_weight="0.5"android:inputType="textPersonName"android:hint="Search Location" /> < Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="0.5"android:onClick="searchLocation"android:text="Search" /> < /LinearLayout> < /fragment>

build.gradle
【Kotlin Android Google地图搜索位置】在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'}

strings.xml
< resources> < string name="app_name"> Kotlin Google Search Location< /string> < string name="title_activity_maps"> Google Search Location< /string> < /resources>

google_map_api.xml
将Google Map API密钥放置在res / values / google_map_api.xml文件中。
< resources> < !--https://console.developers.google.com/flows/enableapi?apiid=maps_android_backend&keyType=CLIENT_SIDE_ANDROID&r=20:0B:71:3B:B2:46:75:A1:87:78:2E:4C:49:3F:E3:B6:FD:2D:76:D3%3Bexample.srcmini.com.kotlingooglesearchlocationAlternatively, follow the directions here:https://developers.google.com/maps/documentation/android/start#get-keyOnce you have your key (it starts with "AIza"), replace the "google_maps_key"string in this file.--> < string name="google_maps_key" templateMergeStrategy="preserve" translatable="false"> AIzaSyCKvLn2KTPKD_-REPLACE-WITH-YOUR-API< /string> < /resources>

MapsActivity.kt
在MapsActivity.kt类文件中添加以下代码。
package example.srcmini.com.kotlingooglesearchlocationimport android.os.Bundleimport com.google.android.gms.maps.CameraUpdateFactoryimport com.google.android.gms.maps.GoogleMapimport com.google.android.gms.maps.OnMapReadyCallbackimport com.google.android.gms.maps.SupportMapFragmentimport com.google.android.gms.maps.model.LatLngimport com.google.android.gms.maps.model.MarkerOptionsimport android.location.Addressimport android.location.Geocoderimport android.os.Buildimport android.support.v4.app.FragmentActivityimport com.google.android.gms.common.api.GoogleApiClientimport com.google.android.gms.maps.model.BitmapDescriptorFactoryimport com.google.android.gms.maps.model.Markerimport com.google.android.gms.location.LocationServicesimport android.location.Locationimport android.Manifestimport android.content.pm.PackageManagerimport android.support.v4.content.ContextCompatimport android.view.Viewimport android.widget.EditTextimport android.widget.Toastimport com.google.android.gms.common.ConnectionResultimport com.google.android.gms.location.LocationListenerimport com.google.android.gms.location.LocationRequestimport java.io.IOExceptionclass MapsActivity() : FragmentActivity(), OnMapReadyCallback, LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {private var mMap: GoogleMap? = nullinternal lateinit var mLastLocation: Locationinternal var mCurrLocationMarker: Marker? = nullinternal var mGoogleApiClient: GoogleApiClient? = nullinternal lateinit var mLocationRequest: LocationRequestoverride 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 SupportMapFragmentmapFragment.getMapAsync(this)}override fun onMapReady(googleMap: GoogleMap) {mMap = googleMapif (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}}@Synchronizedprotected 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 = 1000mLocationRequest.fastestInterval = 1000mLocationRequest.priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACYif (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 = locationif (mCurrLocationMarker != null) {mCurrLocationMarker!!.remove()}//Place current location markerval 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 cameramMap!!.moveCamera(CameraUpdateFactory.newLatLng(latLng))mMap!!.animateCamera(CameraUpdateFactory.zoomTo(11f))//stop location updatesif (mGoogleApiClient != null) {LocationServices.getFusedLocationProviderClient(this)}}override fun onConnectionFailed(connectionResult: ConnectionResult) {}fun searchLocation(view: View) {val locationSearch:EditText = findViewById< EditText> (R.id.editText)lateinit var location: Stringlocation = locationSearch.text.toString()var addressList: List< Address> ? = nullif (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()}}}

AndroidManifest.xml
< ?xml version="1.0" encoding="utf-8"?> < manifest xmlns:android="http://schemas.android.com/apk/res/android"package="example.srcmini.com.kotlingooglesearchlocation"> < uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> < uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> < uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> < uses-permission android:name="android.permission.INTERNET" /> < applicationandroid: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"> < meta-dataandroid:name="com.google.android.geo.API_KEY"android:value="http://www.srcmini.com/@string/google_maps_key" /> < activityandroid:name=".MapsActivity"android:label="@string/title_activity_maps"> < intent-filter> < action android:name="android.intent.action.MAIN" /> < category android:name="android.intent.category.LAUNCHER" /> < /intent-filter> < /activity> < /application> < /manifest>

输出:
注意:请在实际的Android设备上进行检查, 以获取最佳输出结果。
Kotlin Android Google地图搜索位置

文章图片
Kotlin Android Google地图搜索位置

文章图片

    推荐阅读