Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.paikariwala.user.views;
- import androidx.annotation.NonNull;
- import androidx.annotation.Nullable;
- import androidx.appcompat.app.AlertDialog;
- import androidx.appcompat.app.AppCompatActivity;
- import android.Manifest;
- import android.annotation.SuppressLint;
- import android.content.Intent;
- import android.location.Location;
- import android.location.LocationListener;
- import android.location.LocationManager;
- import android.media.MediaRouter2;
- import android.net.Uri;
- import android.os.Bundle;
- import android.os.PersistableBundle;
- import android.provider.Settings;
- import android.util.Log;
- import android.view.View;
- import android.widget.TextView;
- import android.widget.Toast;
- import com.directions.route.AbstractRouting;
- import com.directions.route.Route;
- import com.directions.route.RouteException;
- import com.directions.route.Routing;
- import com.directions.route.RoutingListener;
- import com.google.android.gms.common.ConnectionResult;
- import com.google.android.gms.common.api.GoogleApiClient;
- import com.google.android.gms.common.api.Status;
- import com.google.android.gms.location.FusedLocationProviderClient;
- import com.google.android.gms.maps.CameraUpdate;
- import com.google.android.gms.maps.CameraUpdateFactory;
- import com.google.android.gms.maps.GoogleMap;
- import com.google.android.gms.maps.MapFragment;
- import com.google.android.gms.maps.MapView;
- 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.android.gms.maps.model.MarkerOptions;
- import com.google.android.gms.maps.model.Polyline;
- import com.google.android.gms.maps.model.PolylineOptions;
- import com.google.android.libraries.places.api.model.Place;
- import com.google.android.libraries.places.api.model.TypeFilter;
- import com.google.android.libraries.places.widget.Autocomplete;
- import com.google.android.libraries.places.widget.AutocompleteActivity;
- import com.google.android.libraries.places.widget.model.AutocompleteActivityMode;
- import com.google.android.material.button.MaterialButton;
- import com.google.android.material.floatingactionbutton.FloatingActionButton;
- import com.google.android.material.snackbar.Snackbar;
- import com.karumi.dexter.Dexter;
- import com.karumi.dexter.PermissionToken;
- import com.karumi.dexter.listener.PermissionDeniedResponse;
- import com.karumi.dexter.listener.PermissionGrantedResponse;
- import com.karumi.dexter.listener.PermissionRequest;
- import com.karumi.dexter.listener.single.PermissionListener;
- import com.paikariwala.user.R;
- import org.jetbrains.annotations.NotNull;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.List;
- public class DeliveryActivity extends AppCompatActivity implements OnMapReadyCallback, RoutingListener {
- private static final String TAG = "DeliveryActivity";
- boolean isPermissionGranted;
- GoogleMap mGoogleMap;
- TextView dropOffLocation,pickUpLocation;
- FloatingActionButton gps;
- private FusedLocationProviderClient mLocationClient;
- LocationManager locationManager;
- public int GPS_REQUEST_CODE = 9001;
- private static int AUTOCOMPLETE_REQUEST_CODE = 1;
- private List<Polyline> polylines=null;
- protected LatLng start=null;
- protected LatLng end=null;
- Place place;
- Location location;
- MaterialButton confirm_button;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_delivery);
- gps = findViewById(R.id.gps_button);
- confirm_button = findViewById(R.id.confirm_button);
- SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_view);
- checkMyPermission();
- mLocationClient = new FusedLocationProviderClient(this);
- if(isPermissionGranted){
- if(isGPSenable()){
- mapFragment.getMapAsync(this);
- getCurrentLocation();
- }
- }
- gps.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- getCurrentLocation();
- }
- });
- dropOffLocation = findViewById(R.id.dropoff_location);
- dropOffLocation.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- List<Place.Field> fields = Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.ADDRESS, Place.Field.LAT_LNG);
- Intent intent = new Autocomplete.IntentBuilder(AutocompleteActivityMode.FULLSCREEN, fields)
- .setCountries(Arrays.asList("BD"))
- .build(DeliveryActivity.this);
- startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE);
- }
- });
- confirm_button.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- end=place.getLatLng();
- mGoogleMap.clear();
- start=new LatLng(location.getLatitude(),location.getLongitude());
- Findroutes(start,end);
- }
- });
- }
- private boolean isGPSenable(){
- LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
- boolean providerEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
- if(providerEnable){
- return true;
- } else{
- AlertDialog alertDialog = new AlertDialog.Builder(this).setTitle("GPS Permission")
- .setMessage("Please Enable GPS")
- .setPositiveButton("Yes",((dialogInterface, i) -> {
- Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
- startActivityForResult(intent,GPS_REQUEST_CODE);
- })).setCancelable(false).show();
- }
- return false;
- }
- @SuppressLint("MissingPermission")
- private void getCurrentLocation() {
- mLocationClient.getLastLocation().addOnCompleteListener(task ->{
- if(task.isSuccessful()){
- location = task.getResult();
- gotoLocation(location.getLatitude(),location.getLongitude());
- }
- });
- }
- private void gotoLocation(double latitude, double longitude) {
- LatLng latLng = new LatLng(latitude,longitude);
- CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng,18);
- mGoogleMap.moveCamera(cameraUpdate);
- mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
- mGoogleMap.addMarker(new MarkerOptions().position(latLng));
- }
- private void checkMyPermission() {
- Dexter.withContext(this).withPermission(Manifest.permission.ACCESS_FINE_LOCATION).withListener(new PermissionListener() {
- @Override
- public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
- Toast.makeText(DeliveryActivity.this, "Permission Granted", Toast.LENGTH_SHORT).show();
- isPermissionGranted = true;
- }
- @Override
- public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {
- Intent intent = new Intent();
- intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
- Uri uri = Uri.fromParts("package",getPackageName(),"");
- intent.setData(uri);
- startActivity(intent);
- }
- @Override
- public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
- permissionToken.continuePermissionRequest();
- }
- }).check();
- }
- @SuppressLint("MissingPermission")
- @Override
- public void onMapReady(@NonNull @NotNull GoogleMap googleMap) {
- mGoogleMap = googleMap;
- //mGoogleMap.setMyLocationEnabled(true);
- }
- @Override
- protected void onPause() {
- super.onPause();
- //To Do
- }
- @Override
- protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
- if(requestCode == GPS_REQUEST_CODE){
- locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
- boolean providerEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
- if(providerEnable){
- Toast.makeText(this, "GPS is enable", Toast.LENGTH_SHORT).show();
- }else{
- Toast.makeText(this, "GPS is not enable", Toast.LENGTH_SHORT).show();
- }
- }
- else if(requestCode == AUTOCOMPLETE_REQUEST_CODE){
- if (resultCode == RESULT_OK) {
- place = Autocomplete.getPlaceFromIntent(data);
- CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(place.getLatLng(),18);
- mGoogleMap.moveCamera(cameraUpdate);
- dropOffLocation.setText(place.getAddress());
- mGoogleMap.addMarker(new MarkerOptions().position(place.getLatLng()));
- Log.i(TAG, "Place: " + place.getName() + ", " + place.getId());
- } else if (resultCode == AutocompleteActivity.RESULT_ERROR) {
- // TODO: Handle the error.
- Status status = Autocomplete.getStatusFromIntent(data);
- Log.i(TAG, status.getStatusMessage());
- } else if (resultCode == RESULT_CANCELED) {
- // The user canceled the operation.
- }
- }
- }
- public void Findroutes(LatLng Start, LatLng End)
- {
- if(Start==null || End==null) {
- Toast.makeText(DeliveryActivity.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("AIzaSyC1XQfCxmTZiEpDS7RMG3c0-4cVYwZwesM") //also define your api key here.
- .build();
- routing.execute();
- }
- }
- @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(DeliveryActivity.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(18);
- 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 = mGoogleMap.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");
- mGoogleMap.addMarker(startMarker);
- //Add Marker on route ending position
- MarkerOptions endMarker = new MarkerOptions();
- endMarker.position(polylineEndLatLng);
- endMarker.title("Destination");
- mGoogleMap.addMarker(endMarker);
- }
- @Override
- public void onRoutingCancelled() {
- Findroutes(start,end);
- }
- }
Add Comment
Please, Sign In to add comment