calculate distance from source to destination in android code example
Example: calculate distance from source to destination in android
//import this
import com.google.maps.android.SphericalUtil;
public class Detailed extends AppCompatActivity {
//define object for storing latitude and longitude coordinates
LatLng YourLocationData;
LatLng DestinationData;
Double Distance;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//button casting
Button btn=findViewById(R.id.button2);
//setting cooridnates
YourLocationData = new LatLng(15.40757526659319, 73.99194849921113);
DestinationData = new LatLng(15.366058435624439, 73.94238788088278);
//OnClick listener for functionality of button
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//checking permission for location
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;
}
distance = SphericalUtil.computeDistanceBetween(YourLocationData,DestinationData);
Toast.makeText(MainActivity.this, "Distance between Your Location and Destination is \n " + String.format("%.2f", distance / 1000) + "km", Toast.LENGTH_SHORT).show();
});
}
}