· 4 years ago · Jun 24, 2021, 07:28 PM
1package com.paikariwala.user.views;
2
3import androidx.annotation.NonNull;
4import androidx.annotation.Nullable;
5import androidx.appcompat.app.AlertDialog;
6import androidx.appcompat.app.AppCompatActivity;
7
8import android.Manifest;
9import android.annotation.SuppressLint;
10import android.content.Intent;
11import android.location.Location;
12import android.location.LocationListener;
13import android.location.LocationManager;
14import android.media.MediaRouter2;
15import android.net.Uri;
16import android.os.Bundle;
17import android.os.PersistableBundle;
18import android.provider.Settings;
19import android.util.Log;
20import android.view.View;
21import android.widget.TextView;
22import android.widget.Toast;
23
24import com.directions.route.AbstractRouting;
25import com.directions.route.Route;
26import com.directions.route.RouteException;
27import com.directions.route.Routing;
28import com.directions.route.RoutingListener;
29import com.google.android.gms.common.ConnectionResult;
30import com.google.android.gms.common.api.GoogleApiClient;
31import com.google.android.gms.common.api.Status;
32import com.google.android.gms.location.FusedLocationProviderClient;
33import com.google.android.gms.maps.CameraUpdate;
34import com.google.android.gms.maps.CameraUpdateFactory;
35import com.google.android.gms.maps.GoogleMap;
36import com.google.android.gms.maps.MapFragment;
37import com.google.android.gms.maps.MapView;
38import com.google.android.gms.maps.OnMapReadyCallback;
39import com.google.android.gms.maps.SupportMapFragment;
40import com.google.android.gms.maps.model.LatLng;
41import com.google.android.gms.maps.model.MarkerOptions;
42import com.google.android.gms.maps.model.Polyline;
43import com.google.android.gms.maps.model.PolylineOptions;
44import com.google.android.libraries.places.api.model.Place;
45import com.google.android.libraries.places.api.model.TypeFilter;
46import com.google.android.libraries.places.widget.Autocomplete;
47import com.google.android.libraries.places.widget.AutocompleteActivity;
48import com.google.android.libraries.places.widget.model.AutocompleteActivityMode;
49import com.google.android.material.button.MaterialButton;
50import com.google.android.material.floatingactionbutton.FloatingActionButton;
51import com.google.android.material.snackbar.Snackbar;
52import com.karumi.dexter.Dexter;
53import com.karumi.dexter.PermissionToken;
54import com.karumi.dexter.listener.PermissionDeniedResponse;
55import com.karumi.dexter.listener.PermissionGrantedResponse;
56import com.karumi.dexter.listener.PermissionRequest;
57import com.karumi.dexter.listener.single.PermissionListener;
58import com.paikariwala.user.R;
59
60import org.jetbrains.annotations.NotNull;
61
62import java.util.ArrayList;
63import java.util.Arrays;
64import java.util.List;
65
66public class DeliveryActivity extends AppCompatActivity implements OnMapReadyCallback, RoutingListener {
67
68 private static final String TAG = "DeliveryActivity";
69 boolean isPermissionGranted;
70 GoogleMap mGoogleMap;
71 TextView dropOffLocation,pickUpLocation;
72 FloatingActionButton gps;
73 private FusedLocationProviderClient mLocationClient;
74 LocationManager locationManager;
75 public int GPS_REQUEST_CODE = 9001;
76 private static int AUTOCOMPLETE_REQUEST_CODE = 1;
77 private List<Polyline> polylines=null;
78 protected LatLng start=null;
79 protected LatLng end=null;
80 Place place;
81 Location location;
82 MaterialButton confirm_button;
83
84 @Override
85 protected void onCreate(Bundle savedInstanceState) {
86 super.onCreate(savedInstanceState);
87 setContentView(R.layout.activity_delivery);
88
89 gps = findViewById(R.id.gps_button);
90 confirm_button = findViewById(R.id.confirm_button);
91
92 SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_view);
93
94 checkMyPermission();
95
96
97 mLocationClient = new FusedLocationProviderClient(this);
98
99 if(isPermissionGranted){
100 if(isGPSenable()){
101 mapFragment.getMapAsync(this);
102 getCurrentLocation();
103 }
104 }
105
106 gps.setOnClickListener(new View.OnClickListener() {
107 @Override
108 public void onClick(View view) {
109 getCurrentLocation();
110 }
111 });
112
113
114 dropOffLocation = findViewById(R.id.dropoff_location);
115 dropOffLocation.setOnClickListener(new View.OnClickListener() {
116 @Override
117 public void onClick(View view) {
118 List<Place.Field> fields = Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.ADDRESS, Place.Field.LAT_LNG);
119 Intent intent = new Autocomplete.IntentBuilder(AutocompleteActivityMode.FULLSCREEN, fields)
120 .setCountries(Arrays.asList("BD"))
121 .build(DeliveryActivity.this);
122 startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE);
123 }
124 });
125
126 confirm_button.setOnClickListener(new View.OnClickListener() {
127 @Override
128 public void onClick(View view) {
129 end=place.getLatLng();
130
131 mGoogleMap.clear();
132
133 start=new LatLng(location.getLatitude(),location.getLongitude());
134 Findroutes(start,end);
135 }
136 });
137 }
138
139 private boolean isGPSenable(){
140 LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
141 boolean providerEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
142 if(providerEnable){
143 return true;
144 } else{
145 AlertDialog alertDialog = new AlertDialog.Builder(this).setTitle("GPS Permission")
146 .setMessage("Please Enable GPS")
147 .setPositiveButton("Yes",((dialogInterface, i) -> {
148 Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
149 startActivityForResult(intent,GPS_REQUEST_CODE);
150 })).setCancelable(false).show();
151 }
152 return false;
153 }
154
155 @SuppressLint("MissingPermission")
156 private void getCurrentLocation() {
157 mLocationClient.getLastLocation().addOnCompleteListener(task ->{
158 if(task.isSuccessful()){
159 location = task.getResult();
160 gotoLocation(location.getLatitude(),location.getLongitude());
161 }
162 });
163 }
164
165 private void gotoLocation(double latitude, double longitude) {
166 LatLng latLng = new LatLng(latitude,longitude);
167 CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng,18);
168 mGoogleMap.moveCamera(cameraUpdate);
169 mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
170 mGoogleMap.addMarker(new MarkerOptions().position(latLng));
171 }
172
173 private void checkMyPermission() {
174 Dexter.withContext(this).withPermission(Manifest.permission.ACCESS_FINE_LOCATION).withListener(new PermissionListener() {
175 @Override
176 public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
177 Toast.makeText(DeliveryActivity.this, "Permission Granted", Toast.LENGTH_SHORT).show();
178 isPermissionGranted = true;
179 }
180
181 @Override
182 public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {
183 Intent intent = new Intent();
184 intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
185 Uri uri = Uri.fromParts("package",getPackageName(),"");
186 intent.setData(uri);
187 startActivity(intent);
188 }
189
190 @Override
191 public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
192 permissionToken.continuePermissionRequest();
193 }
194 }).check();
195 }
196
197 @SuppressLint("MissingPermission")
198 @Override
199 public void onMapReady(@NonNull @NotNull GoogleMap googleMap) {
200 mGoogleMap = googleMap;
201 //mGoogleMap.setMyLocationEnabled(true);
202
203 }
204
205 @Override
206 protected void onPause() {
207 super.onPause();
208 //To Do
209 }
210
211 @Override
212 protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
213 super.onActivityResult(requestCode, resultCode, data);
214 if(requestCode == GPS_REQUEST_CODE){
215 locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
216 boolean providerEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
217
218 if(providerEnable){
219 Toast.makeText(this, "GPS is enable", Toast.LENGTH_SHORT).show();
220 }else{
221 Toast.makeText(this, "GPS is not enable", Toast.LENGTH_SHORT).show();
222 }
223 }
224 else if(requestCode == AUTOCOMPLETE_REQUEST_CODE){
225 if (resultCode == RESULT_OK) {
226 place = Autocomplete.getPlaceFromIntent(data);
227 CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(place.getLatLng(),18);
228 mGoogleMap.moveCamera(cameraUpdate);
229 dropOffLocation.setText(place.getAddress());
230 mGoogleMap.addMarker(new MarkerOptions().position(place.getLatLng()));
231 Log.i(TAG, "Place: " + place.getName() + ", " + place.getId());
232 } else if (resultCode == AutocompleteActivity.RESULT_ERROR) {
233 // TODO: Handle the error.
234 Status status = Autocomplete.getStatusFromIntent(data);
235 Log.i(TAG, status.getStatusMessage());
236 } else if (resultCode == RESULT_CANCELED) {
237 // The user canceled the operation.
238 }
239 }
240 }
241
242
243
244 public void Findroutes(LatLng Start, LatLng End)
245 {
246 if(Start==null || End==null) {
247 Toast.makeText(DeliveryActivity.this,"Unable to get location", Toast.LENGTH_LONG).show();
248 }
249 else
250 {
251
252 Routing routing = new Routing.Builder()
253 .travelMode(AbstractRouting.TravelMode.DRIVING)
254 .withListener(this)
255 .alternativeRoutes(true)
256 .waypoints(Start, End)
257 .key("AIzaSyC1XQfCxmTZiEpDS7RMG3c0-4cVYwZwesM") //also define your api key here.
258 .build();
259 routing.execute();
260 }
261 }
262
263 @Override
264 public void onRoutingFailure(RouteException e) {
265 View parentLayout = findViewById(android.R.id.content);
266 Snackbar snackbar= Snackbar.make(parentLayout, e.toString(), Snackbar.LENGTH_LONG);
267 snackbar.show();
268// Findroutes(start,end);
269 }
270
271 @Override
272 public void onRoutingStart() {
273 Toast.makeText(DeliveryActivity.this,"Finding Route...",Toast.LENGTH_LONG).show();
274 }
275
276 //If Route finding success..
277 @Override
278 public void onRoutingSuccess(ArrayList<Route> route, int shortestRouteIndex) {
279
280 CameraUpdate center = CameraUpdateFactory.newLatLng(start);
281 CameraUpdate zoom = CameraUpdateFactory.zoomTo(18);
282 if(polylines!=null) {
283 polylines.clear();
284 }
285 PolylineOptions polyOptions = new PolylineOptions();
286 LatLng polylineStartLatLng=null;
287 LatLng polylineEndLatLng=null;
288
289
290 polylines = new ArrayList<>();
291 //add route(s) to the map using polyline
292 for (int i = 0; i <route.size(); i++) {
293
294 if(i==shortestRouteIndex)
295 {
296 polyOptions.color(getResources().getColor(R.color.colorPrimary));
297 polyOptions.width(7);
298 polyOptions.addAll(route.get(shortestRouteIndex).getPoints());
299 Polyline polyline = mGoogleMap.addPolyline(polyOptions);
300 polylineStartLatLng=polyline.getPoints().get(0);
301 int k=polyline.getPoints().size();
302 polylineEndLatLng=polyline.getPoints().get(k-1);
303 polylines.add(polyline);
304
305 }
306 else {
307
308 }
309
310 }
311
312 //Add Marker on route starting position
313 MarkerOptions startMarker = new MarkerOptions();
314 startMarker.position(polylineStartLatLng);
315 startMarker.title("My Location");
316 mGoogleMap.addMarker(startMarker);
317
318 //Add Marker on route ending position
319 MarkerOptions endMarker = new MarkerOptions();
320 endMarker.position(polylineEndLatLng);
321 endMarker.title("Destination");
322 mGoogleMap.addMarker(endMarker);
323 }
324
325 @Override
326 public void onRoutingCancelled() {
327 Findroutes(start,end);
328 }
329
330}