简体   繁体   English

在Android中获取两个位置之间的距离但不起作用

[英]Getting distance between Two Locations in android but not working

Actually I want to get exact distance between two lat and lang. 实际上,我想获取两个纬度和经度之间的确切距离。 But I have tried three different functions but all are not giving me right distance. 但是我尝试了三种不同的功能,但都无法给我正确的距离。

Here is Code: 这是代码:

 private double distance(double lat1, double lon1, double lat2, double lon2) {

//first formula
        Location startPoint=new Location("locationA");
        startPoint.setLatitude(lat1);
        startPoint.setLongitude(lon1);

        Location endPoint=new Location("locationA");
        endPoint.setLatitude(lat2);
        endPoint.setLongitude(lon2);

        double distancee=startPoint.distanceTo(endPoint);

// second formula
        float[] results=new float[1];
        Location.distanceBetween( lat1,  lon1,  lat2,  lon2, results);
        float result= 0;
        if (results != null) {
            result = results[0];
        }
        double dvar=(double)result;



        //third formula
        double theta = lon1 - lon2;
        double dist = Math.sin(deg2rad(lat1))
                * Math.sin(deg2rad(lat2))
                + Math.cos(deg2rad(lat1))
                * Math.cos(deg2rad(lat2))
                * Math.cos(deg2rad(theta));
        dist = Math.acos(dist);
        dist = rad2deg(dist);
        dist = dist * 60 * 1.1515;

        return (distancee);
    }


    private double deg2rad(double deg) {
        return (deg * Math.PI / 180.0);
    }

    private double rad2deg(double rad) {
        return (rad * 180.0 / Math.PI);
    }

These all are not giving me right distance please guide me how can I perform this goal 这些都不给我正确的距离,请指导我如何实现这个目标

The distance that you are getting is a straight line between the two points, and as you found out by using the tool in GoogleMaps it is correct. 您得到的距离是两点之间的直线,并且通过使用GoogleMaps的工具发现,它是正确的。 In order to get the distance which takes into account the roads and everything else, you will have to use Google Directions Api . 为了获得将道路和其他所有因素都考虑在内的距离,您必须使用Google Directions Api You will need to make an HTTP Request using Retrofit or OkHttp or something else. 您将需要使用RetrofitOkHttp或其他方式发出HTTP请求。

In your request, you will need to provide origin and destination and as a response, you will get a bunch of information, including the distance, you can find more info on the docs website that I linked. 在您的请求中,您将需要提供起点和目的地,作为回应,您将获得一堆信息,包括距离,您可以在我链接的docs网站上找到更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM