向地图添加多个地理围栏

Adding multiple Geofence to a map

到目前为止,我可以借助此 tutorial 向地图添加单个地理围栏。实际上,我在地图点击事件中向地图添加标记,允许我在触摸时添加多个标记。我不想将地理围栏添加到我添加的所有标记中。我尝试对上述教程的特定方法进行一些更改,如

ArrayList<LatLng> locs= new ArrayList<LatLng>();
    // Create a marker for the geofence creation
private void markerForGeofence(LatLng latLng) {
    Log.i(TAG, "markerForGeofence(" + latLng + ")");
    String title = latLng.latitude + ", " + latLng.longitude;
    // Define marker options
    MarkerOptions markerOptions = new MarkerOptions()
            .position(latLng)
            .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE))
            .title(title);
    if (map != null) {
        // Remove last geoFenceMarker
      //  if (geoFenceMarker != null)
      //      geoFenceMarker.remove();

        geoFenceMarker = map.addMarker(markerOptions);  
        gfmarkr.add(geoFenceMarker);
    }
}
...
   // Start Geofence creation process
private void startGeofence() {
    Log.i(TAG, "startGeofence()");
    if (geoFenceMarker != null) {
        for (int i = 0; i < gfmarkr.size(); i++) {
            Geofence geofence = createGeofence(locs.get(i), GEOFENCE_RADIUS);
            GeofencingRequest geofenceRequest = createGeofenceRequest(geofence);
            addGeofence(geofenceRequest);
        }
    } else {
        Log.e(TAG, "Geofence marker is null");
    }
}

简而言之,添加多个地理围栏的方法是什么。任何解决方案都会有很大帮助。谢谢。

当您获取位置更新时,如果您所有地理围栏的 ArrayList 大于 100,请删除所有被监控的地理围栏,然后使用 harvesine 公式计算最近的 100 个地理围栏:

public static final double R = 6372.8; // In kilometers

public static double haversine(double lat1, double lon1, double lat2, double lon2) {
  double dLat = Math.toRadians(lat2 - lat1);
  double dLon = Math.toRadians(lon2 - lon1);
  lat1 = Math.toRadians(lat1);
  lat2 = Math.toRadians(lat2);

  double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
  double c = 2 * Math.asin(Math.sqrt(a));
  return R * c;
}

这将为您提供两个位置之间的距离。之后,您可以将该距离与地理围栏区域半径进行比较,以了解是否在该区域内。 注意:如果您的半径以米为单位,则此距离将以公里为单位,然后只需将 haversine 方法的结果乘以 1000,以便将其转换为米。

Reference

已解决。我将 locs.get(i) 传递给负责创建特定地理围栏的所有方法,并将其用作位置的参考点。另外,我删除了语句

 if (geoFenceLimits != null)
    geoFenceLimits.remove();

来自 drawGeofence() 方法。