Skip to content

hamza-ameer/GoogleMaps-Find-Routes

 
 

Repository files navigation

GoogleMaps-Find-Routes

Add the following dependencies in you app level gradle file if not exists:

implementation 'com.google.android.gms:play-services-maps:16.1.0'
implementation 'com.github.jd-alexander:library:1.1.0'
implementation 'com.google.android.material:material:1.1.0'

Get Your Google Maps Api Key From Google Cloud Platform.

  1. login to your google account and follow this link: https://console.cloud.google.com/google/maps-apis/

  2. Must enable the following services:

    1. Maps SDK Android.
    2. Directions Api.
    3. Enable Billing.

Add the following permissions and meta-data tags in application tag in your menifest file:

<uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

//add these meta-data in application tag
 <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="Your Api Key" />
   <!-- Don't use my api key, it will not work for you.-->



<meta-data android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

Add the following fragment in your activity_main.xml file to show Map.

<fragment xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/map"
tools:context=".MainActivity"
android:name="com.google.android.gms.maps.SupportMapFragment" />

Update the your MainActivity.java file with the following code:

 public class MainActivity extends FragmentActivity implements OnMapReadyCallback,
    GoogleApiClient.OnConnectionFailedListener, RoutingListener {

//google map object
private GoogleMap mMap;

//current and destination location objects
Location myLocation=null;
Location destinationLocation=null;
protected LatLng start=null;
protected LatLng end=null;

//to get location permissions.
private final static int LOCATION_REQUEST_CODE = 23;
boolean locationPermission=false;

//polyline object
private List<Polyline> polylines=null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //request location permission.
    requestPermision();

    //init google map fragment to show map.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}

private void requestPermision()
{
    if(ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_COARSE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                LOCATION_REQUEST_CODE);
    }
    else{
        locationPermission=true;
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case LOCATION_REQUEST_CODE: {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //if permission granted.
                locationPermission=true;
                    getMyLocation();

            } else {
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }
    }
}

//to get user location
private void getMyLocation(){
    mMap.setMyLocationEnabled(true);
    mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
        @Override
        public void onMyLocationChange(Location location) {

            myLocation=location;
            LatLng ltlng=new LatLng(location.getLatitude(),location.getLongitude());
            CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(
                    ltlng, 16f);
            mMap.animateCamera(cameraUpdate);
        }
    });

    //get destination location when user click on map
    mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
        @Override
        public void onMapClick(LatLng latLng) {

          end=latLng;

            mMap.clear();

            start=new LatLng(myLocation.getLatitude(),myLocation.getLongitude());
            //start route finding
            Findroutes(start,end);
        }
    });

}


@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

        getMyLocation();

}


// function to find Routes.
public void Findroutes(LatLng Start, LatLng End)
{
    if(Start==null || End==null) {
        Toast.makeText(MainActivity.this,"Unable to get location",Toast.LENGTH_LONG).show();
    }
    else
    {

        Routing routing = new Routing.Builder()
                .travelMode(AbstractRouting.TravelMode.DRIVING)
                .withListener(this)
                .alternativeRoutes(true)
                .waypoints(Start, End)
                .key("Your Api Key")  //also define your api key here.
                .build();
        routing.execute();
    }
}

//Routing call back functions.
@Override
public void onRoutingFailure(RouteException e) {
    View parentLayout = findViewById(android.R.id.content);
    Snackbar snackbar= Snackbar.make(parentLayout, e.toString(), Snackbar.LENGTH_LONG);
    snackbar.show();
//    Findroutes(start,end);
}

@Override
public void onRoutingStart() {
      Toast.makeText(MainActivity.this,"Finding Route...",Toast.LENGTH_LONG).show();
}

//If Route finding success..
@Override
public void onRoutingSuccess(ArrayList<Route> route, int shortestRouteIndex) {

    CameraUpdate center = CameraUpdateFactory.newLatLng(start);
    CameraUpdate zoom = CameraUpdateFactory.zoomTo(16);
    if(polylines!=null) {
        polylines.clear();
    }
    PolylineOptions polyOptions = new PolylineOptions();
    LatLng polylineStartLatLng=null;
    LatLng polylineEndLatLng=null;


    polylines = new ArrayList<>();
    //add route(s) to the map using polyline
    for (int i = 0; i <route.size(); i++) {

        if(i==shortestRouteIndex)
        {
            polyOptions.color(getResources().getColor(R.color.colorPrimary));
            polyOptions.width(7);
            polyOptions.addAll(route.get(shortestRouteIndex).getPoints());
            Polyline polyline = mMap.addPolyline(polyOptions);
            polylineStartLatLng=polyline.getPoints().get(0);
            int k=polyline.getPoints().size();
            polylineEndLatLng=polyline.getPoints().get(k-1);
            polylines.add(polyline);

        }
        else {

        }

    }

    //Add Marker on route starting position
    MarkerOptions startMarker = new MarkerOptions();
    startMarker.position(polylineStartLatLng);
    startMarker.title("My Location");
    mMap.addMarker(startMarker);

    //Add Marker on route ending position
    MarkerOptions endMarker = new MarkerOptions();
    endMarker.position(polylineEndLatLng);
    endMarker.title("Destination");
    mMap.addMarker(endMarker);
}

@Override
public void onRoutingCancelled() {
    Findroutes(start,end);
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    Findroutes(start,end);

 }
}

  1. Test your App and Enjoy :)

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published