Android how to use location.distanceTo ()

I use fragement, I need to get my current location (lat and lng) and I need to calculate my current location with the destination.

Could you give me a hand. What is the best way to calculate location:

How can I get the distance from my current location and destination 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); 
+6
source share
3 answers

Try

 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 
+11
source

You can use the static Location: distanceBetween method to get the distance between two locations.

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

doc: here

+3
source

Use the Direction API to find the distance from your current location to your destination. It returns a JSON object as a distance, which gives you the distance in a mile, you can parse this JSON and display it on the screen of your application.

For official Google documentation read here .

And for the tutorial read here .

Hope this helps !!!

0
source

Source: https://habr.com/ru/post/981699/


All Articles