简体   繁体   中英

Getting absurd values when trying to calculate distance between two coordinates in Android

I am trying to find distance between two coordinates using latitudes and longitudes.I am using the following method:

private double distance(double lat1, double lon1, double lat2, double lon2, char unit) {
          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;
          if (unit == 'K') {
            dist = dist * 1.609344;
          } else if (unit == 'N') {
            dist = dist * 0.8684;
            }
          return (dist);
        }

        /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
        /*::  This function converts decimal degrees to radians             :*/
        /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
        private double deg2rad(double deg) {
          return (deg * Math.PI / 180.0);
        }

        /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
        /*::  This function converts radians to decimal degrees             :*/
        /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
        private double rad2deg(double rad) {
          return (rad * 180.0 / Math.PI);
        }

I am getting the current latitude and longitude from bundle from a previous activity and i am calling the method as follows:

String parameter=""+distance(current_latitude,current_longitude,Double.parseDouble(store_list.get(position).store_latitude),Double.parseDouble(store_list.get(position).store_longitude),'K');

But i am getting absurd results values like 8500 etc.Please help

Consider using the method provided by the Location class: http://developer.android.com/reference/android/location/Location.html#distanceBetween(double, double, double, double, float[])

public static void distanceBetween (double startLatitude, double startLongitude, double endLatitude, double endLongitude, float[] results)

Parameters
startLatitude   the starting latitude
startLongitude  the starting longitude
endLatitude the ending latitude
endLongitude    the ending longitude
results an array of floats to hold the results

usage:

float[] results = new float[3];
Location.distanceBetween(current_latitude, current_longitude, Double.parseDouble(store_list.get(position).store_latitude), Double.parseDouble(store_list.get(position).store_longitude, results);
float distanceMeters = results[0];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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