Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android how to use location.distanceTo()

I am using a fragement, I need to get my currently Location (lat and lng) and I need to calculate my currently location with the destination location.

Can you pls give me a hand. what is the best way to calculate the location:

How can I get the distance from my currently location and the destination location using lat and lng ;

    LocationManager locationManager;
    Location locatio;



locationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);

location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);





String product_latitude     = "3.121191";
            String product_longtitude   = "101.673298";

            Double latitude     = Double.valueOf(product_latitude);
            Double longtitude   = Double.valueOf(product_longtitude);

            // Calculate the Distance
            String product_distance = location.distanceTo(latitude, longtitude);
like image 230
Thiago Avatar asked Jan 29 '15 07:01

Thiago


People also ask

How do I find location data on Android?

There are two ways to get the current location of any Android device: Android's Location Manager API. Fused Location Provider: Google Play Services Location APIs.

Which method is invoked when a new location is available?

abstract void onLocationChanged(Location location) This callback method is used for receiving notifications from the LocationClient when the location has changed.

What is geo location in Android?

The Geolocation API returns a location and accuracy radius based on information about cell towers and WiFi nodes that the mobile client can detect. This document describes the protocol used to send this data to the server and to return a response to the client.


2 Answers

Try this

double latitude=lat;
double longitude=lng;    
float distance=0;
Location crntLocation=new Location("crntlocation");
crntLocation.setLatitude(currentLatitude);
crntLocation.setLongitude(currentLongitude);

Location newLocation=new Location("newlocation");
newLocation.setLatitude(latitude);
newLocation.setLongitude(longitude);


//float distance = crntLocation.distanceTo(newLocation);  in meters
distance =crntLocation.distanceTo(newLocation) / 1000; // in km
like image 88
Jai Rajesh Avatar answered Oct 15 '22 19:10

Jai Rajesh


You can use static method of Location: distanceBetween to get distance between 2 locations.

float [] results = new float[5]; 
Location.distanceBetween(startLatitude, startLongitude, endLatitude,
endLongitude, results)

doc: here

like image 41
Chi Minh Trinh Avatar answered Oct 15 '22 19:10

Chi Minh Trinh