get Distance in M or KM for two locations - Android android.location

Android examples for android.location:Location

Description

get Distance in M or KM for two locations

Demo Code

import android.location.Location;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.NumberFormat;

public class Main{

    public static String getDistanceTo(Location start, Location end) {

        if (start == null || end == null)
            return "";
        double distance = start.distanceTo(end);
        return getDistanceTo(distance);

    }//w w  w  .  jav a  2 s.c om
    public static String getDistanceTo(double distance) {

        String result = "";
        DecimalFormat dF = new DecimalFormat("00");

        dF.applyPattern("0");

        if (distance < 1000)
            result = dF.format(distance) + "m";
        else {
            distance = distance / 1000.0;
            result = dF.format(distance) + "km";
        }

        return result;
    }

}

Related Tutorials