Android 如何检查lat,long是否在我的地理围栏lat,long,半径内
我想在城市里做一个圆形的土工栅栏,我希望这个土工栅栏有2公里宽,我想知道是否有用户在这个土工栅栏里 我所做的Android 如何检查lat,long是否在我的地理围栏lat,long,半径内,android,google-maps,kotlin,google-maps-api-3,android-geofence,Android,Google Maps,Kotlin,Google Maps Api 3,Android Geofence,我想在城市里做一个圆形的土工栅栏,我希望这个土工栅栏有2公里宽,我想知道是否有用户在这个土工栅栏里 我所做的 private fun checkIfInsideGeoFence(){ geofenceList.add(Geofence.Builder() // Set the request ID of the geofence. This is a string to identify this // geofe
private fun checkIfInsideGeoFence(){
geofenceList.add(Geofence.Builder()
// Set the request ID of the geofence. This is a string to identify this
// geofence.
.setRequestId("New York")
// Set the circular region of this geofence.
.setCircularRegion(
40.6882657,
-73.9398756,
2000F)
// Create the geofence.
.build())
geofencingClient.addGeofences(getGeofencingRequest(),geofencePendingIntent).addOnSuccessListener {
fusedLocationClient.lastLocation
.addOnSuccessListener { location : Location? ->
// Got last known location, here I need to check if its inside the geofence
}
}.addOnFailureListener{
}
}
private fun getGeofencingRequest(): GeofencingRequest {
return GeofencingRequest.Builder().apply {
setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER)
addGeofences(geofenceList)
}.build()
}
private val geofencePendingIntent: PendingIntent by lazy {
//Here I dont use a brodcast receiver since I dont need to know if the user enters or leaves the area, just if its inside
PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
我需要知道里面的情况
fusedLocationClient.lastLocation
.addOnSuccessListener { location : Location? ->
// Got last known location, here I need to check if its inside the geofence
}
如何知道用户是否处于该特定比率最简单的方法是检查中心lat long与当前lat long之间的距离,并查看距离是否<2000 mts
fusedLocationClient.lastLocation
.addOnSuccessListener { location : Location? ->
val results = FloatArray(1)
Location.distanceBetween(
40.6882657,
-73.9398756,
location!!.latitude,
location.longitude,
results
)
val distanceInMeters = results[0]
val isWithin2km = distanceInMeters < 2000
if(isWithin2km){
navigateTo()
}else{
startActivity(Intent(this,ActivityGeoFenceError::class.java))
finish()
}
}
fusedLocationClient.lastLocation
.addOnSuccessListener{位置:位置?->
val结果=浮点数组(1)
位置,距离(
40.6882657,
-73.9398756,
位置,纬度,
地点,经度,
结果
)
val distanceInMeters=结果[0]
val在2km以内=距离(米)<2000
如果(在2公里以内){
导航()
}否则{
startActivity(Intent(此,ActivityGeoFenceError::class.java))
完成()
}
}
基于@CoffeeBreak的方法,还可以使用实例方法来减少冗长。类似这样的扩展函数形式:
fun Location.checkIsInBound(radius: Int,center:Location):Boolean
= this.distanceTo(center)<radius
fusedLocationClient.lastLocation
.addOnSuccessListener { location : Location? ->
val isWithin2km = location?.checkIsInBound(2000,center) }
fun Location.checkIsInBond(半径:Int,中心:Location):布尔值
=此。距离(中心)
val isWithin2km=位置?.CheckIsInBond(2000,中心)}
除了使用位置API之外,你还可以使用谷歌地图实用库的代码> CalpalUTIL/<代码>,但是它以<代码> LATLNG < /代码>作为输入。
如果你已经自行解决了这个问题,请考虑将你自己的答案标记为正确。它帮助其他开发人员了解您的答案,知道它解决了您的问题。谢谢大家!@咖啡休息你也能查一下我的问题吗你也能查一下我的帖子吗