Skip to content

Commit d694eb9

Browse files
committed
Complete Frisbee application.
1 parent 3cf99ac commit d694eb9

File tree

7 files changed

+128
-5
lines changed

7 files changed

+128
-5
lines changed

app/src/main/java/spartons/com/frisbee/activities/main/ui/MainActivity.java

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import android.support.annotation.NonNull;
1111
import android.support.annotation.Nullable;
1212
import android.support.v4.app.ActivityCompat;
13+
import android.widget.ProgressBar;
1314
import android.widget.RelativeLayout;
1415
import android.widget.TextView;
1516
import com.google.android.gms.location.LocationServices;
@@ -35,8 +36,10 @@
3536

3637
import static android.content.pm.PackageManager.PERMISSION_DENIED;
3738
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
39+
import static android.view.View.GONE;
40+
import static android.view.View.VISIBLE;
3841

39-
public class MainActivity extends BaseActivity implements GoogleMap.OnCameraIdleListener {
42+
public class MainActivity extends BaseActivity implements GoogleMap.OnCameraIdleListener, GoogleMap.OnCameraMoveStartedListener {
4043

4144
private static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 5655;
4245

@@ -52,6 +55,8 @@ public class MainActivity extends BaseActivity implements GoogleMap.OnCameraIdle
5255
MarkerRepo markerRepo;
5356

5457
private TextView currentPlaceTextView;
58+
private TextView pinTimeTextView;
59+
private ProgressBar pinProgressLoader;
5560

5661
private GoogleMap googleMap;
5762
private Marker currentLocationMarker;
@@ -88,7 +93,10 @@ protected void onCreate(@Nullable Bundle savedInstanceState) {
8893
viewModel.reverseGeocodeResult
8994
.observe(this, placeName -> currentPlaceTextView.setText(placeName));
9095
viewModel.currentLocation
91-
.observe(this, location -> {
96+
.observe(this, __ -> {
97+
Location location = new Location("");
98+
location.setLatitude(37.422);
99+
location.setLongitude(-122.084);
92100
if (firstTimeFlag) {
93101
firstTimeFlag = false;
94102
animateCamera(location);
@@ -102,10 +110,18 @@ protected void onCreate(@Nullable Bundle savedInstanceState) {
102110
viewModel.insertDriverMarker(markerPair.first, marker);
103111
}
104112
});
113+
viewModel.calculateDistance
114+
.observe(this, distance -> {
115+
pinTimeTextView.setText(distance);
116+
pinTimeTextView.setVisibility(VISIBLE);
117+
pinProgressLoader.setVisibility(GONE);
118+
});
105119
}
106120

107121
private void initViews() {
108122
currentPlaceTextView = findViewById(R.id.currentPlaceTextView);
123+
pinProgressLoader = findViewById(R.id.pinProgressLoader);
124+
pinTimeTextView = findViewById(R.id.pinTimeTextView);
109125
findViewById(R.id.currentLocationImageButton).setOnClickListener(__ -> {
110126
Location location = viewModel.currentLocation.getValue();
111127
if (location == null || googleMap == null) return;
@@ -140,13 +156,21 @@ private void setGoogleMapSettings() {
140156
googleMapHelper.defaultMapSettings(googleMap);
141157
googleMap.setMapStyle(MapStyleOptions.loadRawResourceStyle(this, R.raw.style_json));
142158
googleMap.setOnCameraIdleListener(this);
159+
googleMap.setOnCameraMoveStartedListener(this);
143160
}
144161

145162
@Override
146163
public void onCameraIdle() {
147164
if (googleMap == null) return;
148165
LatLng latLng = googleMap.getCameraPosition().target;
149166
viewModel.makeReverseGeocodeRequest(latLng, geocoder);
167+
viewModel.onCameraIdle(latLng);
168+
}
169+
170+
@Override
171+
public void onCameraMoveStarted(int i) {
172+
pinTimeTextView.setVisibility(GONE);
173+
pinProgressLoader.setVisibility(VISIBLE);
150174
}
151175

152176
@Override
@@ -171,6 +195,8 @@ protected void onDestroy() {
171195
currentLocationMarker = null;
172196
appRxSchedulers = null;
173197
googleMap = null;
198+
markerRepo = null;
199+
driverRepo = null;
174200
geocoder = null;
175201
}
176202
}

app/src/main/java/spartons/com/frisbee/activities/main/viewModel/MainActivityViewModel.java

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,13 @@
1717
import com.google.android.gms.maps.model.MarkerOptions;
1818
import com.google.firebase.database.DatabaseReference;
1919
import com.google.firebase.database.FirebaseDatabase;
20+
import com.google.maps.DistanceMatrixApi;
21+
import com.google.maps.PendingResult;
22+
import com.google.maps.model.DistanceMatrix;
23+
import com.google.maps.model.TravelMode;
24+
import io.reactivex.Completable;
2025
import io.reactivex.Observable;
26+
import io.reactivex.Single;
2127
import io.reactivex.disposables.CompositeDisposable;
2228
import spartons.com.frisbee.lsitener.FirebaseObjectValueListener;
2329
import spartons.com.frisbee.lsitener.LatLngInterpolator;
@@ -38,6 +44,7 @@ public class MainActivityViewModel extends ViewModel implements FirebaseObjectVa
3844

3945
private MediatorLiveData<String> _reverseGeocodeResult = new MediatorLiveData<>();
4046
private MediatorLiveData<Location> _currentLocation = new MediatorLiveData<>();
47+
private MediatorLiveData<String> _calculateDistance = new MediatorLiveData<>();
4148
private MediatorLiveData<Pair<String, MarkerOptions>> _addNewMarker = new MediatorLiveData<>();
4249

4350
private LocationCallback locationCallback = new LocationCallback() {
@@ -61,6 +68,7 @@ public void onLocationResult(LocationResult locationResult) {
6168
public LiveData<String> reverseGeocodeResult = _reverseGeocodeResult;
6269
public LiveData<Location> currentLocation = _currentLocation;
6370
public LiveData<Pair<String, MarkerOptions>> addNewMarker = _addNewMarker;
71+
public LiveData<String> calculateDistance = _calculateDistance;
6472

6573
public MainActivityViewModel(UiHelper uiHelper, FusedLocationProviderClient locationProviderClient, DriverRepo driverRepo, MarkerRepo markerRepo, AppRxSchedulers appRxSchedulers, GoogleMapHelper googleMapHelper) {
6674
this.uiHelper = uiHelper;
@@ -78,6 +86,42 @@ public void requestLocationUpdates() {
7886
locationProviderClient.requestLocationUpdates(uiHelper.getLocationRequest(), locationCallback, Looper.myLooper());
7987
}
8088

89+
public void onCameraIdle(LatLng latLng) {
90+
compositeDisposable.add(Completable.fromRunnable(() -> {
91+
if (!driverRepo.allItems().isEmpty()) {
92+
Driver driver = driverRepo.getNearestDriver(latLng.latitude, latLng.longitude);
93+
if (driver != null)
94+
calculateDistance(latLng, driver);
95+
} else _calculateDistance.postValue("No \n Car");
96+
}).subscribe(() -> {
97+
}, Throwable::printStackTrace));
98+
}
99+
100+
private void calculateDistance(LatLng latLng, Driver driver) {
101+
compositeDisposable.add(Single.<DistanceMatrix>create(emitter -> {
102+
String destination[] = {String.valueOf(driver.lat) + ",".concat(String.valueOf(driver.lng))};
103+
String origins[] = {String.valueOf(latLng.latitude) + ",".concat(String.valueOf(latLng.longitude))};
104+
DistanceMatrixApi.getDistanceMatrix(googleMapHelper.geoContextDistanceApi(), origins, destination)
105+
.mode(TravelMode.DRIVING)
106+
.setCallback(new PendingResult.Callback<DistanceMatrix>() {
107+
@Override
108+
public void onResult(DistanceMatrix result) {
109+
emitter.onSuccess(result);
110+
}
111+
112+
@Override
113+
public void onFailure(Throwable e) {
114+
emitter.onError(e);
115+
}
116+
});
117+
}).subscribeOn(appRxSchedulers.io())
118+
.subscribe(result -> {
119+
if (result == null || result.rows[0] == null || result.rows[0].elements[0] == null)
120+
return;
121+
_calculateDistance.postValue(String.valueOf(result.rows[0].elements[0].duration.humanReadable));
122+
}, Throwable::printStackTrace));
123+
}
124+
81125
@Override
82126
public void onDriverOnline(Driver driver) {
83127
if (driverRepo.insert(driver)) {

app/src/main/java/spartons/com/frisbee/collections/DriverCollection.java

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
import spartons.com.frisbee.util.AppRxSchedulers;
88

99
import javax.inject.Inject;
10+
import java.util.ArrayList;
11+
import java.util.Collections;
1012
import java.util.List;
1113
import java.util.concurrent.CopyOnWriteArrayList;
1214
import java.util.stream.Collector;
@@ -85,5 +87,25 @@ private Driver getStreamAbleDriver(String driverId) {
8587
}
8688
);
8789
}
88-
}
8990

91+
public Driver getNearestDriver(double lat, double lng) {
92+
List<Driver> filteredDriverList = sortDriversByDistance(lat, lng);
93+
if (filteredDriverList.size() == 0)
94+
return null;
95+
return filteredDriverList.get(0);
96+
}
97+
98+
private List<Driver> sortDriversByDistance(final double curLat, final double curLng) {
99+
List<Driver> tempDrivers = new ArrayList<>(driverList);
100+
Collections.sort(tempDrivers, (driver1, driver2) -> {
101+
double distance1 = measureDriverDistanceInMeters(driver1.lat, driver1.lng, curLat, curLng);
102+
double distance2 = measureDriverDistanceInMeters(driver2.lat, driver2.lng, curLat, curLng);
103+
return Double.compare(distance1, distance2);
104+
});
105+
return tempDrivers;
106+
}
107+
108+
private double measureDriverDistanceInMeters(double driverLatitude, double driverLongitude, double currentLatitude, double currentLongitude) {
109+
return 1000.0 * (6371.0 * Math.acos(Math.cos(Math.toRadians(currentLatitude)) * Math.cos(Math.toRadians(driverLatitude)) * Math.cos(Math.toRadians(driverLongitude) - Math.toRadians(currentLongitude)) + Math.sin(Math.toRadians(currentLatitude)) * Math.sin(Math.toRadians(driverLatitude))));
110+
}
111+
}

app/src/main/java/spartons/com/frisbee/repo/DriverRepo.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,10 @@ public Driver get(String s) {
2828
return driverCollection.getDriverWithId(s);
2929
}
3030

31+
public Driver getNearestDriver(double lat, double lng) {
32+
return driverCollection.getNearestDriver(lat, lng);
33+
}
34+
3135
public List<Driver> allItems() {
3236
return driverCollection.allDriver();
3337
}

app/src/main/java/spartons/com/frisbee/util/GoogleMapHelper.java

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import com.google.android.gms.maps.model.CameraPosition;
1010
import com.google.android.gms.maps.model.LatLng;
1111
import com.google.android.gms.maps.model.MarkerOptions;
12+
import com.google.maps.GeoApiContext;
1213
import spartons.com.frisbee.R;
1314

1415
import javax.inject.Inject;
@@ -24,6 +25,7 @@ public GoogleMapHelper(Resources resources) {
2425

2526
private static final int ZOOM_LEVEL = 18;
2627
private static final int TILT_LEVEL = 25;
28+
private static GeoApiContext.Builder geoApiContextBuilder = new GeoApiContext.Builder();
2729

2830
/**
2931
* @param location in which position to Zoom the camera.
@@ -77,4 +79,24 @@ public MarkerOptions getDriverMarkerOptions(LatLng position, float angle) {
7779
return options;
7880
}
7981

82+
/**
83+
* @return the google distance api key.
84+
*/
85+
86+
private String distanceApi() {
87+
return resources.getString(R.string.google_distance_matrix_api_key);
88+
}
89+
90+
/**
91+
* The function returns the ${[GeoApiContext]} with distance api key.
92+
*
93+
* @return the ${[GeoApiContext]} with distance api.
94+
*/
95+
96+
public GeoApiContext geoContextDistanceApi() {
97+
return geoApiContextBuilder
98+
.apiKey(distanceApi())
99+
.build();
100+
}
101+
80102
}
Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
<?xml version="1.0" encoding="utf-8"?>
22
<resources>
3-
<string name="google_maps_api_key">AIzaSyDLJaKB*************tvNMRGNuxk</string>
3+
44
// change it with your own google maps api key
5+
<string name="google_maps_api_key">AIza**********************************Nuxk</string>
6+
7+
// change it with your google distance matrix api key.
8+
<string name="google_distance_matrix_api_key">AIza**********************************L0</string>
9+
510
</resources>

app/src/main/res/values/strings.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,6 @@
55
<string name="location_content">This app wants to change your device settings use GPS,Wi-Fi and cell networks for
66
your location
77
</string>
8-
<string name="frisbee_needs_your_location_in_order_to_find_your_captain_according_to_current_location">Qaswa needs your location in order to find nearby drivers and your current location .</string>
8+
<string name="frisbee_needs_your_location_in_order_to_find_your_captain_according_to_current_location">Frisbee needs your location in order to find nearby drivers and your current location .</string>
99
<string name="no_car">No Car</string>
1010
</resources>

0 commit comments

Comments
 (0)