Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to Calculate Distance Between two Locations in Android?

  • Last Updated : 24 Jan, 2021

We have seen many apps that use Google Maps. These maps are used to indicate places on Google Maps and also we can use this to calculate the distance between two locations. In this article, we will take a look at calculating the distance between two locations in Android. 

What we are going to build in this article? 

We will be building a simple application in which we will be displaying a simple map and on our app launch, we will show a Toast message with a distance between two locations on our Map. Below is the video in which we will get to see what we are going to build in this article. We are going to calculate the distance between Sydney and Brisbane. Note that we are going to implement this project using the Java language. 

Want a more fast-paced & competitive environment to learn the fundamentals of Android?
Click here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Make sure to select Maps Activity while creating a new Project.



Step 2: Generating an API key for using Google Maps

To generate the API key for Maps you may refer to How to Generate API Key for Using Google Maps in Android. After generating your API key for Google Maps. We have to add this key to our Project. For adding this key in our app navigate to the values folder > google_maps_api.xml file and at line 23 you have to add your API key in the place of YOUR_API_KEY

Step 3: Adding a dependency to calculate the distance between two locations

Navigate to the app > Gradle Scripts > build.gradle file and add below dependency in the dependencies section. 

implementation ‘com.google.maps.android:android-maps-utils:0.4+’

After adding the below dependency now sync your project. After adding this dependency now move towards the MapsActivity.java file for showing a toast message. 

Step 4: Working with the MapsActivity.java file

Go to the MapsActivity.java file and refer to the following code. Below is the code for the MapsActivity.java file. Comments are added inside the code to understand the code in more detail.

Java




import android.os.Bundle;
import android.widget.Toast;
  
import androidx.fragment.app.FragmentActivity;
  
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.maps.android.SphericalUtil;
  
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
  
    private GoogleMap mMap;
      
    // below are the latitude and longitude 
    // of 2 different locations.
    LatLng sydney = new LatLng(-34, 151);
    LatLng Brisbane = new LatLng(-27.470125, 153.021072);
    Double distance;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified 
        // when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }
  
    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        // on below line we are calculating the distance between sydney and brisbane
        distance = SphericalUtil.computeDistanceBetween(sydney, Brisbane);
          
        // in below line we are displaying a toast 
        // message with distance between two locations.
        // in our distance we are dividing it by 1000 to
        // make in km and formatting it to only 2 decimal places.
        Toast.makeText(this, "Distance between Sydney and Brisbane is \n " + String.format("%.2f", distance / 1000) + "km", Toast.LENGTH_SHORT).show();
    }
}

After adding this code. Now run your app and see the output of the app.

Output:

Note: In the Google Developer Console (https://console.developers.google.com), ensure that the “Google Maps Android API v2” is enabled. And also ensure that your API Key exists.




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!