Is there any API for calculating Geofence breach other than Android API's

蓝咒 提交于 2019-12-01 01:48:45

You can implement it yourself, without using any frameworks, it's very easy...

I presume that you want to check if you're inside a circle geofence or not.

To do this, just calculate the distance between the center of the circle and your location (longitude, latitude). If the distance is smaller than your circle radius, then you're inside the geofence, otherwise you're outside the geofence.

Like this:

    boolean checkInside(Circle circle, double longitude, double latitude) {
        return calculateDistance(
            circle.getLongitude(), circle.getLatitude(), longitude, latitude
        ) < circle.getRadius();}

To calculate the distance between two points, you can use this:

double calculateDistance(
  double longitude1, double latitude1, 
  double longitude2, double latitude2) {
    double c = 
        Math.sin(Math.toRadians(latitude1)) *
        Math.sin(Math.toRadians(latitude2)) +
            Math.cos(Math.toRadians(latitude1)) *
            Math.cos(Math.toRadians(latitude2)) *
            Math.cos(Math.toRadians(longitude2) - 
                Math.toRadians(longitude1));
    c = c > 0 ? Math.min(1, c) : Math.max(-1, c);
    return 3959 * 1.609 * 1000 * Math.acos(c);
}

This formula is called the Haversine formula. It takes into account the earths curvation. The results are in meters.

I've also described it on my blog:

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!