在Google Maps android上放置点击监听器
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在Google Maps android上放置点击监听器相关的知识,希望对你有一定的参考价值。
我有一个带有地图片段的android应用。该地图显示了地点,我正在寻找一种添加监听器的方法,以便在用户点击它们时获得该地点。
我发现的最相关的信息是建议添加一个用于单击地图的听众,获取长声和纬度,然后根据该位置搜索地点。我以为可以使用FetchPlaceRequest
来做到这一点,但是在实例化时这似乎也首先需要placeId
。
我错过了一些基本的东西吗?
编辑
包含地图的片段的代码(我认为实现PlaceSelectionlistener可以完成工作)
class MapFragment : Fragment(), OnMapReadyCallback, GoogleMap.OnMarkerClickListener,
PlaceSelectionListener, KoinComponent {
private lateinit var mapViewModel: MapViewModel
private lateinit var map: GoogleMap
private var fusedLocationClient: FusedLocationProviderClient? = null
private var locationRequest: LocationRequest? = null
private var locationCallback: LocationCallback? = null
private val permissionsUtils : PermissionsUtils by inject()
private val preferencesUtils : PreferencesUtils by inject { parametersOf(activity!!.applicationContext)}
private var root : View? = null
private val defaultZoom : Float = 16f
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
mapViewModel = ViewModelProviders.of(this).get(MapViewModel::class.java)
root = inflater.inflate(R.layout.fragment_map, container, false)
if (canAccessLocation()) {
initialiseMap(true)
} else {
val permissions = arrayOf(Manifest.permission.ACCESS_FINE_LOCATION)
requestPermissions(permissions, PermissionRequests.FineLocation.value)
}
return root
}
override fun onMarkerClick(p0: Marker?) = false
override fun onMapReady(googleMap: GoogleMap) {
map = googleMap
map.setMapStyle(MapStyleOptions
.loadRawResourceStyle(activity!!.applicationContext, preferencesUtils.mapMode))
map.uiSettings.isZoomControlsEnabled = true
if (canAccessLocation()){
map.isMyLocationEnabled = true
map.uiSettings.isMyLocationButtonEnabled = true
}
map.setOnMarkerClickListener(this)
}
override fun onRequestPermissionsResult(requestCode: Int,
permissions: Array<String>, grantResults: IntArray) {
when (requestCode) {
PermissionRequests.FineLocation.value -> {
val permissionGranted = grantResults.isNotEmpty()
&& grantResults[0] == PackageManager.PERMISSION_GRANTED
initialiseMap(permissionGranted)
}
}
}
override fun onPause() {
super.onPause()
fusedLocationClient?.removeLocationUpdates(locationCallback)
}
override fun onResume() {
super.onResume()
requestLocationUpdates()
}
override fun onPlaceSelected(status: Place) {
val toast = Toast.makeText(activity!!.applicationContext,""+ status!!.name + status!!.latLng, Toast.LENGTH_LONG)
toast.setGravity(Gravity.TOP, 0, 0)
toast.show()
}
override fun onError(status: Status) {
Toast.makeText(activity!!.applicationContext,"" + status.toString(), Toast.LENGTH_LONG)
.show()
}
private fun initialiseMap(withLocation: Boolean) {
val mapFragment = childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
if (!withLocation) {
return
}
requestLocationUpdates()
}
private fun requestLocationUpdates() {
if (fusedLocationClient == null) {
fusedLocationClient = LocationServices.getFusedLocationProviderClient(activity!!.applicationContext)
}
locationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult) {
val locationList = locationResult.locations
if (locationList.size > 0) {
val location = locationList[locationList.size - 1]
val latLng = LatLng(location.latitude, location.longitude)
map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, defaultZoom))
}
}
}
fusedLocationClient?.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper())
locationRequest = LocationRequest()
locationRequest?.interval = 1800000
locationRequest?.fastestInterval = 1800000
locationRequest?.priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY
fusedLocationClient?.lastLocation?.addOnCompleteListener(Activity()) { task ->
if (task.isSuccessful && task.result != null) {
val latLong = LatLng(task.result!!.latitude, task.result!!.longitude)
map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLong, defaultZoom))
}
}
}
private fun canAccessLocation(): Boolean {
return permissionsUtils.hasPermission(activity!!.applicationContext, Manifest.permission.ACCESS_FINE_LOCATION)
}
}
因为您无法管理MapView
(MapFragment
)上显示的位置,并且其标记不可单击(且无法自定义),恕我直言,更好的方法是像Google Maps styling一样通过this隐藏“默认”位置标记的Jozef:
- 像这样创建JSON文件src main res raw map_style.json:
[ { featureType: "poi", elementType: "labels", stylers: [ { visibility: "off" } ] } ]
- 将地图样式添加到
GoogleMap
googleMap.setMapStyle(MapStyleOptions.loadRawResourceStyle(getContext(), R.raw.map_style));
然后,从Place Search URL请求中通过Google Places API到达附近的地方:
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=<LAT_LNG>&types=point_of_interest&radius=<RADIUS_IN_METERS>&sensor=false&key=<YOUR_APP_KEY>
解析它并以编程方式在地图上显示所需的位置,作为可自定义和可点击的Google Maps标记。这种方法不仅可以让您通过默认onMarkerClick()
处理标记点击,还可以管理场所的数量和类型,标记图标设计等。也无需每次用户单击地图时都创建请求并处理其响应。
注意!附近的URL请求仅返回20个地方,要加载更多数据,您应该使用响应的onMarkerClick()
标记中的字符串值,并通过next_page_token
参数将其传递给下一个请求:
pagetoken
以上是关于在Google Maps android上放置点击监听器的主要内容,如果未能解决你的问题,请参考以下文章
用户如何通过点击 google maps android 添加标记?
Google Maps Android API - 如何在拖动时移动标记的锚点
Google Maps Android API v2 - 带有可点击按钮的信息窗口