在项目中添加谷歌地图
集成前的准备工作,可看上一篇博客Android 集成google地图 准备工作 在app build.gradle中添加下面的sdk,记得启用api
implementation 'com.google.android.gms:play-services-maps:17.0.1'
implementation 'com.google.maps.android:android-maps-utils:2.2.0'
在需要显示地图的地方,在布局中添加如下代码
<fragment
android:id="@+id/mapview"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
这样就可以显示出google地图来了,不过效果是这样 现在添加个定位,并显示到当前定位来. 在app build.gradle中添加,记得启用这个api
implementation 'com.google.android.gms:play-services-location:15.0.1'
在AndroidManifest.xm中添加如下权限
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
在activityd的onCreate()中添加如下代码
val mapFragment: SupportMapFragment = supportFragmentManager.findFragmentById(R.id.mapview) as SupportMapFragment
mapFragment.getMapAsync(this)
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
实现onMapReady()
override fun onMapReady(p0: GoogleMap) {
mGoogleMap = p0
getDeviceLocation()
}
实现获取定位,并移动地图。需要先动态获取定位权限
var locationCallback: LocationCallback? = null
@SuppressLint("MissingPermission")
private fun getDeviceLocation() {
try {
val locationRequest = LocationRequest().apply {
interval = 5000
fastestInterval = 5000
priority = LocationRequest.PRIORITY_HIGH_ACCURACY
}
ocationCallback = object: LocationCallback() {
override fun onLocationResult(p0: LocationResult?) {
if (p0 != null ){
//获取到当前位置,将地图移至定位处并将地图放大14倍
mGoogleMap?.moveCamera(CameraUpdateFactory.newLatLngZoom(LatLng(p0.lastLocation.latitude, p0.lastLocation.longitude),14f))
mGoogleMap?.uiSettings?.isMyLocationButtonEnabled = false
//移除callBack,不然还会继续获取定位
fusedLocationProviderClient?.removeLocationUpdates(locationCallback)
val bitmap = BitmapFactory.decodeResource(this@GoogleMapDemoActivity.resources,R.drawable.icon_current_location)
//清空之前添加的标记
mGoogleMap?.clear()
//添加当前位置的标记
mGoogleMap?.addMarker(MarkerOptions().position(LatLng(lat, lng)).icon(
BitmapDescriptorFactory.fromBitmap(bitmap)))
}
}
override fun onLocationAvailability(p0: LocationAvailability?) {
//当前定位不可用
if (p0?.isLocationAvailable != true){
}
fusedLocationProviderClient?.removeLocationUpdates(locationCallback)
}
}
fusedLocationProviderClient?.requestLocationUpdates(locationRequest,locationCallback,
Looper.myLooper())
}catch (e: Exception){
}
}
运行效果如下 使用Geocoder反向地理编码
private fun latlngToAddress(lat: Double,lng: Double){
val geocoder = Geocoder(this)
try {
val result = geocoder.getFromLocation(lat,lng,1)
if (result != null && result.isNotEmpty()){
val addressName = result[0].featureName
}
}catch (e: Exception){
}
}
|