Distance between two location in Android map

后端 未结 4 656
误落风尘
误落风尘 2021-01-07 10:22

How to calculate distance between 2 location in android map & output must display in textview or any ?

4条回答
  •  一向
    一向 (楼主)
    2021-01-07 10:39

    /**
     * Calculate the distance between 2 points based on their GeoPoint coordinates. 
    * Return the value in Km or miles based on the unit input * @param gp1 (GeoPoint): First point. * @param gp2 (GeoPoint): Second point. * @param unit (char): Unit of measurement: 'm' for miles and 'k' for Km. * @return (double): The distance in miles or Km. */ public static double getDistance(GeoPoint gp1, GeoPoint gp2, char unit) { //Convert from degrees to radians final double d2r = Math.PI / 180.0; //Change lat and lon from GeoPoint E6 format final double lat1 = gp1.getLatitudeE6() / 1E6; final double lat2 = gp2.getLatitudeE6() / 1E6; final double lon1 = gp1.getLongitudeE6() / 1E6; final double lon2 = gp2.getLongitudeE6() / 1E6; //The difference between latitudes and longitudes double dLat = Math.abs(lat1 - lat2) * d2r; double dLon = Math.abs(lon1 - lon2) * d2r; double a = Math.pow(Math.sin(dLat / 2.0), 2) + Math.cos(lat1 * d2r) * Math.cos(lat2 * d2r) * Math.pow(Math.sin(dLon / 2.0), 2); double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); //Return the distance return (unit == 'm' ? 3956 : 6367) * c; } //End getDistance() TextView textView.setText("" + getDistance(gp1, gp2, 'k'));

提交回复
热议问题