Reputation: 416
So far I'm able to add single geofence to the map with help of this tutorial. Actually I'm adding markers to the map on map click event allowing me to add multiple markers on touch. I wan't to add geofence to all the markers that I'm adding. I've tried making few changes in particular methods of the above tutorial as
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");
}
}
In short what is the method of adding more than one geofence. Any solution will be of great help. Thankyou.
Upvotes: 0
Views: 2698
Reputation: 416
It is solved. I passed locs.get(i)
to all the methods that are responsible for creating a particular Geofence and used it as a point of reference for position. Also, I removed the statements
if (geoFenceLimits != null)
geoFenceLimits.remove();
from drawGeofence()
method.
Upvotes: 1
Reputation: 287
When you get a location update, if the ArrayList of all your geofences is more than 100, remove all geofences been monitored and then calculate the 100 nearest geofences using the harvesine formula:
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;
}
That will give you the distance between the two locations. After that you could compare that distance with the geofence region radius to know if is inside the region. Note: This distance will be in kilometers if your radius is on meters then just multiply the haversine method result with 1000 so that it's converted to meters.
Upvotes: 0