如何检查lat,long是否在我的围栏内lat,long,radius

时间:2020-04-07 15:03:15

标签: 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
                // 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
                    }

如何知道用户是否处于特定比例

2 个答案:

答案 0 :(得分:0)

最简单的方法是检查中心经纬度到当前经纬度之间的距离,并查看该距离是否小于2000 mts

data "aws_subnet" "example" {
  for_each = data.aws_subnet_ids.example.ids
  id       = each.value
}

答案 1 :(得分:0)

基于@CoffeeBreak 的方法,您还可以使用实例方法 distanceTo 以使其不那么冗长。类似这样的扩展函数形式:

fun Location.checkIsInBound(radius: Int,center:Location):Boolean
        =  this.distanceTo(center)<radius

fusedLocationClient.lastLocation
        .addOnSuccessListener { location : Location? ->
        val isWithin2km = location?.checkIsInBound(2000,center) }

除了使用 Location API 的 distanceTo 外,您还可以使用 Google Map Utility Library 的 SphericalUtilcomputeDistanceBetween,但它需要 LatLng 作为输入。