I know that I can get distance with google api and it is very good
But is it slow sometimes and not possible for my app
Is there any way to get distance between two location?
I know that I can get distance with google api and it is very good
But is it slow sometimes and not possible for my app
Is there any way to get distance between two location?
You could easily get the lastKnownLocation, add the co-ordinates to an ArrayList and then measure the distance between the points in that list as shown below:
Prerequisites:
Add permissions to manifest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> Import Gradle Dependencies:
compile 'com.google.android.gms:play-services-location:10.2.1' Add this class to your project:
Github: android-maps-utils : SphericalUtil.java
Implement LocationListener in your Activity:
public class myClass extends Activity implements LocationListener { Define your global Variables:
private LocationManager locationManager; private String provider; private ArrayList<LatLng> coordList = new ArrayList<String>(); Get Initial Location (in onCreate() or onClick()):
locationManager = (LocationManager) getActivity().getApplicationContext().getSystemService(Context.LOCATION_SERVICE); // Define the criteria how to select the locatioin provider -> use // default Criteria criteria = new Criteria(); provider = locationManager.getBestProvider(criteria, false); Location location = locationManager.getLastKnownLocation(provider); if (coordList != null && !coordList.isEmpty()) { coordList.get(0); } else { coordList.add(0, new LatLng(location.getLatitude(), location.getLongitude())); } if (location != null) { onLocationChanged(location); } getLocationUpdates(); create a getLocationUpdates() method:
private void getLocationUpdates() { if (locationManager != null) { checkPermission(); locationManager.requestLocationUpdates(provider, ONE_SECOND, ONE_METER, this); } } Request location updates from your locationManager (make sure you requestPermission for Android 6.0 and up)
@Override public void onResume() { super.onResume(); getLocationUpdates(); } Use the SphericalUtil class to compute the distance within the ArrayList inside the onLocationChange function.
@Override public void onLocationChanged(Location location) { double distance = SphericalUtil.computeLength(coordList); distance = round(distance, 2) / 1000; distanceOutput.setText(distance + "km"); } Add the round functionality:
public static double round(double value, int places) { if (places < 0) throw new IllegalArgumentException(); BigDecimal bd = new BigDecimal(value); bd = bd.setScale(places, RoundingMode.FLOOR); return bd.doubleValue(); } This will get the distance between start and end points in km and round it down to two decimal places, feel free to convert them into any other unit of distance depending on your use-case.
Google Distance matrix API need to use for the correct distance between places.