distance ofyour location to destination android code example

Example: distance between your location to destination android

import com.google.maps.android.SphericalUtil;

 private FusedLocationProviderClient fusedLocationClient;
    LatLng yourLocation;
    LatLng Destination=new LatLng(15.389230635580095, 73.92281848312571);
    Double distance;






//inside oncreate


 btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

          

        if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
       
            return;
        }
                fusedLocationClient.getLastLocation()
                .addOnSuccessListener(MainActivity.this, new OnSuccessListener<Location>() {
                    @Override
                    public void onSuccess(Location location) {
                        // Got last known location. In some rare situations this can be null.
                        if (location != null) {
                           
                            Double lat =location.getLatitude();
                            Double longi = location.getLongitude();

                            yourLocationPlz(lat,longi);

                            
                            distance = SphericalUtil.computeDistanceBetween(yourLocation,Destination);
                            Toast.makeText(MainActivity.this, "Distance between Your Location and Destination is \n " + String.format("%.2f", distance / 1000) + "km", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

            }
        });







    



public void  yourLocationPlz(Double Latitude,Double Longitude){

         yourLocation=new LatLng(Latitude,Longitude);


}

Tags:

Java Example