From 08d9543e3b99e15573840cf3565a33cda378b51c Mon Sep 17 00:00:00 2001 From: Bipin Date: Mon, 4 Jan 2021 11:01:23 +0100 Subject: [PATCH 01/21] RouteTest made --- .../java/com/a1/nextlocation/RouteTest.java | 86 +++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 app/src/test/java/com/a1/nextlocation/RouteTest.java diff --git a/app/src/test/java/com/a1/nextlocation/RouteTest.java b/app/src/test/java/com/a1/nextlocation/RouteTest.java new file mode 100644 index 0000000..1d2dd3c --- /dev/null +++ b/app/src/test/java/com/a1/nextlocation/RouteTest.java @@ -0,0 +1,86 @@ +package com.a1.nextlocation; + +import com.a1.nextlocation.data.Location; +import com.a1.nextlocation.data.Route; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.*; + +public class RouteTest { + + @Test + public void GetNameTest(){ + Route route = new Route("testName"); + String expected = "testName"; + assertEquals(expected, route.getName()); + } + + @Test + public void getLocationsTest(){ + Route route = new Route("testName"); + List expected = new ArrayList<>(); + + assertEquals(expected, route.getLocations()); + } + + @Test + public void SetLocationsTest(){ + Route route = new Route("testName"); + List testList = new ArrayList<>(); + testList.add(new Location("name1", "coord1", "desc1", null)); + testList.add(new Location("name2", "coord2", "desc2", null)); + testList.add(new Location("name3", "coord3", "desc3", null)); + + List expectedBefore = new ArrayList<>(); + List expectedAfter = testList; + + assertEquals(expectedBefore, route.getLocations()); + route.setLocations(testList); + assertEquals(expectedAfter, route.getLocations()); + } + + @Test + public void AddLocationTest(){ + Route route = new Route("testName"); + Location testLocation = new Location("testLocationName", "testCoordinates", "testDescription", null); + + List expectedBefore = new ArrayList<>(); + List expectedAfter = new ArrayList<>(); + expectedAfter.add(testLocation); + + assertEquals(expectedBefore, route.getLocations()); + route.addLocation(testLocation); + assertEquals(expectedAfter, route.getLocations()); + } + + @Test + public void totalDistanceTest(){ + Route route = new Route("testName"); + float testDistance = 523; + + float expectedBefore = 0; + float expectedAfter = 523; + + assertEquals(expectedBefore, route.getTotalDistance(), 0.01); + route.setTotalDistance(testDistance); + assertEquals(expectedAfter, route.getTotalDistance(), 0.01); + } + + @Test + public void totalTimeTest(){ + Route route = new Route("testName"); + int testTime = 36; + + int expectedBefore = 0; + int expectedAfter = 36; + + assertEquals(expectedBefore, route.getTotalTime()); + route.setTotalTime(testTime); + assertEquals(expectedAfter, route.getTotalTime()); + } + +} From eea66fd153398741191f0506374ceee72e33215a Mon Sep 17 00:00:00 2001 From: Robin Koedood Date: Mon, 4 Jan 2021 11:38:54 +0100 Subject: [PATCH 02/21] [ADD] Data and Coupon Tests --- .../com/a1/nextlocation/CouponTestClass.java | 32 ++++++++ .../com/a1/nextlocation/DataTestClass.java | 81 +++++++++++++++++++ 2 files changed, 113 insertions(+) create mode 100644 app/src/test/java/com/a1/nextlocation/CouponTestClass.java create mode 100644 app/src/test/java/com/a1/nextlocation/DataTestClass.java diff --git a/app/src/test/java/com/a1/nextlocation/CouponTestClass.java b/app/src/test/java/com/a1/nextlocation/CouponTestClass.java new file mode 100644 index 0000000..068b814 --- /dev/null +++ b/app/src/test/java/com/a1/nextlocation/CouponTestClass.java @@ -0,0 +1,32 @@ +package com.a1.nextlocation; + +import com.a1.nextlocation.data.Coupon; + +import org.junit.Before; +import org.junit.Test; +import static org.junit.Assert.*; + + +public class CouponTestClass { + private Coupon testCoupon; + + @Before + public void init(){ + testCoupon = new Coupon("TESTCODE", "REWARDISTRUE"); + } + + @Test + public void testSetCode() { + testCoupon.setCode("testing"); + String expected = "testing"; + assertEquals(expected, testCoupon.getCode()); + } + + @Test + public void testSetReward() { + testCoupon.setReward("testreward"); + String expected = "testreward"; + assertNotNull(testCoupon.getReward()); + assertEquals(expected, testCoupon.getReward()); + } +} diff --git a/app/src/test/java/com/a1/nextlocation/DataTestClass.java b/app/src/test/java/com/a1/nextlocation/DataTestClass.java new file mode 100644 index 0000000..576f00a --- /dev/null +++ b/app/src/test/java/com/a1/nextlocation/DataTestClass.java @@ -0,0 +1,81 @@ +package com.a1.nextlocation; + +import com.a1.nextlocation.data.Coupon; +import com.a1.nextlocation.data.Data; +import com.a1.nextlocation.data.Location; +import com.a1.nextlocation.data.Route; + +import org.junit.Before; +import org.junit.Test; +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.List; + +public class DataTestClass { + private Data data; + + @Before + public void init(){ + data = new Data(); + } + + + @Test + public void testSetDistanceTraveled() { + data.setDistanceTraveled(100); + + int expected = 100; + assertEquals(expected, data.getDistanceTraveled(), 0.1); + } + + @Test + public void testSetLocationsVisited() { + data.setLocationsVisited(16); + + int expected = 16; + assertEquals(expected, data.getLocationsVisited()); + } + + @Test + public void testSetTotalTime() { + data.setTotalTime(120); + + int expected = 120; + assertEquals(expected, data.getTotalTime()); + } + + @Test + public void testSetCouponList() { + List expected = new ArrayList<>(); + expected.add(new Coupon("CODE1", "REWARD1")); + expected.add(new Coupon("CODE2", "REWARD2")); + expected.add(new Coupon("CODE3", "REWARD3")); + + data.setCouponList(expected); + assertEquals(expected, data.getCouponList()); + } + + @Test + public void testNextLocation() { + Location expected = new Location("name1", "cord1", "desc1", null); + data.setNextLocation(expected); + assertEquals(expected, data.getNextLocation()); + } + + @Test + public void testLastLocation() { + Location expected = new Location("name2", "cord2", "desc2", null); + data.setLastLocation(expected); + assertEquals(expected, data.getLastLocation()); + } + + @Test + public void testCurrentRoute() { + Route expected = new Route("testRoute1"); + data.setCurrentRoute(expected); + assertEquals(expected, data.getCurrentRoute()); + } + + +} \ No newline at end of file From d433565fefcda28bce92cbfa81928e5889be8c17 Mon Sep 17 00:00:00 2001 From: Sem van der Hoeven Date: Mon, 4 Jan 2021 11:42:34 +0100 Subject: [PATCH 03/21] added parsing of directions response --- .../com/a1/nextlocation/MainActivity.java | 1 + .../nextlocation/fragments/HomeFragment.java | 2 - .../nextlocation/fragments/RouteFragment.java | 19 ++++++ .../nextlocation/json/DirectionsResult.java | 62 +++++++++++++++++++ .../a1/nextlocation/json/DirectionsStep.java | 40 ++++++++++++ .../a1/nextlocation/network/ApiHandler.java | 36 +++++++---- .../network/DirectionsListener.java | 8 +++ 7 files changed, 153 insertions(+), 15 deletions(-) create mode 100644 app/src/main/java/com/a1/nextlocation/json/DirectionsResult.java create mode 100644 app/src/main/java/com/a1/nextlocation/json/DirectionsStep.java create mode 100644 app/src/main/java/com/a1/nextlocation/network/DirectionsListener.java diff --git a/app/src/main/java/com/a1/nextlocation/MainActivity.java b/app/src/main/java/com/a1/nextlocation/MainActivity.java index 9ba6645..aa9d618 100644 --- a/app/src/main/java/com/a1/nextlocation/MainActivity.java +++ b/app/src/main/java/com/a1/nextlocation/MainActivity.java @@ -13,6 +13,7 @@ import com.a1.nextlocation.fragments.HomeFragment; import com.a1.nextlocation.fragments.RouteFragment; import com.a1.nextlocation.fragments.SettingsFragment; import com.a1.nextlocation.fragments.StatisticFragment; +import com.a1.nextlocation.network.ApiHandler; import com.a1.nextlocation.recyclerview.CouponListManager; import com.a1.nextlocation.recyclerview.LocationListManager; import com.a1.nextlocation.recyclerview.RouteListManager; diff --git a/app/src/main/java/com/a1/nextlocation/fragments/HomeFragment.java b/app/src/main/java/com/a1/nextlocation/fragments/HomeFragment.java index 8f5ba7d..d21d925 100644 --- a/app/src/main/java/com/a1/nextlocation/fragments/HomeFragment.java +++ b/app/src/main/java/com/a1/nextlocation/fragments/HomeFragment.java @@ -110,8 +110,6 @@ public class HomeFragment extends Fragment { mapView.getOverlays().add(customOverlay); - - // add the zoom controller IMapController mapController = mapView.getController(); mapController.setZoom(15.0); diff --git a/app/src/main/java/com/a1/nextlocation/fragments/RouteFragment.java b/app/src/main/java/com/a1/nextlocation/fragments/RouteFragment.java index 59043de..a415247 100644 --- a/app/src/main/java/com/a1/nextlocation/fragments/RouteFragment.java +++ b/app/src/main/java/com/a1/nextlocation/fragments/RouteFragment.java @@ -2,19 +2,27 @@ package com.a1.nextlocation.fragments; import android.os.Bundle; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; +import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.a1.nextlocation.R; +import com.a1.nextlocation.json.DirectionsResult; +import com.a1.nextlocation.network.ApiHandler; +import com.a1.nextlocation.network.DirectionsListener; public class RouteFragment extends Fragment { + private static final String TAG = RouteFragment.class.getCanonicalName(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); + ApiHandler.INSTANCE.addListener(this::onDirectionsAvailable); } @@ -24,4 +32,15 @@ public class RouteFragment extends Fragment { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_route, container, false); } + + @Override + public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { + super.onViewCreated(view, savedInstanceState); + + ApiHandler.INSTANCE.getDirections(8.681436,49.41461,8.687872,49.420318); + } + + public void onDirectionsAvailable(DirectionsResult result) { + Log.d(TAG, "onDirectionsAvailable: got result! " + result); + } } \ No newline at end of file diff --git a/app/src/main/java/com/a1/nextlocation/json/DirectionsResult.java b/app/src/main/java/com/a1/nextlocation/json/DirectionsResult.java new file mode 100644 index 0000000..e52caba --- /dev/null +++ b/app/src/main/java/com/a1/nextlocation/json/DirectionsResult.java @@ -0,0 +1,62 @@ +package com.a1.nextlocation.json; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +import java.util.ArrayList; +import java.util.List; + +public class DirectionsResult { + private List steps = new ArrayList<>(); + private double distance; + private double duration; + + public List getSteps() { + return steps; + } + + public void setSteps(List steps) { + this.steps = steps; + } + + public double getDistance() { + return distance; + } + + public void setDistance(double distance) { + this.distance = distance; + } + + public double getDuration() { + return duration; + } + + public void setDuration(double duration) { + this.duration = duration; + } + + public void addStep(DirectionsStep step) { + this.steps.add(step); + } + + public void parse(String json) { + + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + JsonObject features = JsonParser.parseString(json).getAsJsonObject().get("features").getAsJsonArray().get(0).getAsJsonObject(); + JsonObject segment = features.get("properties").getAsJsonObject().getAsJsonArray("segments").get(0).getAsJsonObject(); + + setDistance(segment.get("distance").getAsDouble()); + setDuration(segment.get("duration").getAsDouble()); + + JsonArray steps = segment.getAsJsonArray("steps"); + + for (JsonElement j : steps) { + DirectionsStep step = gson.fromJson(j,DirectionsStep.class); + addStep(step); + } + } +} diff --git a/app/src/main/java/com/a1/nextlocation/json/DirectionsStep.java b/app/src/main/java/com/a1/nextlocation/json/DirectionsStep.java new file mode 100644 index 0000000..64678f8 --- /dev/null +++ b/app/src/main/java/com/a1/nextlocation/json/DirectionsStep.java @@ -0,0 +1,40 @@ +package com.a1.nextlocation.json; + +public class DirectionsStep { + private double distance; + private double duration; + private String instruction; + private String name; + + public double getDistance() { + return distance; + } + + public void setDistance(double distance) { + this.distance = distance; + } + + public double getDuration() { + return duration; + } + + public void setDuration(double duration) { + this.duration = duration; + } + + public String getInstruction() { + return instruction; + } + + public void setInstruction(String instruction) { + this.instruction = instruction; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/app/src/main/java/com/a1/nextlocation/network/ApiHandler.java b/app/src/main/java/com/a1/nextlocation/network/ApiHandler.java index af34416..0bf76dc 100644 --- a/app/src/main/java/com/a1/nextlocation/network/ApiHandler.java +++ b/app/src/main/java/com/a1/nextlocation/network/ApiHandler.java @@ -4,8 +4,11 @@ import android.util.Log; import com.a1.nextlocation.data.Location; import com.a1.nextlocation.data.Route; +import com.a1.nextlocation.json.DirectionsResult; import java.io.IOException; +import java.util.ArrayList; +import java.util.List; import java.util.Objects; import java.util.concurrent.atomic.AtomicReference; @@ -22,21 +25,22 @@ public enum ApiHandler { public static final MediaType JSON = MediaType.get("application/json; charset=utf-8"); private final String BASE_URL = "https://api.openrouteservice.org/v2/directions/"; private final String API_KEY = "5b3ce3597851110001cf6248d4eee2099f724255918adc71cc502b2a"; - private final String DIRECTIONS_MODE = "foot_walking"; + private final String DIRECTIONS_MODE = "foot-walking"; + private List listeners = new ArrayList<>(); private OkHttpClient client = new OkHttpClient(); - public Route getDirections(Location startLocation, Location endLocation) { - return getDirections(startLocation.getCoordinates(),endLocation.getCoordinates()); + public void getDirections(Location startLocation, Location endLocation) { + getDirections(startLocation.getCoordinates(),endLocation.getCoordinates()); } - public Route getDirections(double startLat, double startLong, double endLat, double endLong) { - return getDirections(startLat + "," + startLong, endLat + "," + endLong); + public void getDirections(double startLat, double startLong, double endLat, double endLong) { + getDirections(startLat + "," + startLong, endLat + "," + endLong); } - public Route getDirections(String startLocation, String endLocation) { + public void getDirections(String startLocation, String endLocation) { + String requestUrl = BASE_URL + DIRECTIONS_MODE + "?api_key=" + API_KEY + "&start=" +startLocation + "&end=" + endLocation; - AtomicReference res = null; Thread t = new Thread(() -> { Request request = new Request.Builder().url(requestUrl).build(); @@ -45,6 +49,14 @@ public enum ApiHandler { if (response.body() != null) { String responseString = Objects.requireNonNull(response.body()).string(); Log.d(TAG, "getDirections: got response: " + responseString); + + DirectionsResult result = new DirectionsResult(); + result.parse(responseString); + Log.d(TAG, "getDirections: " + result.getSteps().size()); + + for (DirectionsListener listener : listeners) { + listener.onDirectionsAvailable(result); + } } } catch (IOException e) { @@ -54,12 +66,10 @@ public enum ApiHandler { t.start(); - try { - t.join(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return res.get(); + } + + public void addListener(DirectionsListener listener) { + this.listeners.add(listener); } diff --git a/app/src/main/java/com/a1/nextlocation/network/DirectionsListener.java b/app/src/main/java/com/a1/nextlocation/network/DirectionsListener.java new file mode 100644 index 0000000..28f2305 --- /dev/null +++ b/app/src/main/java/com/a1/nextlocation/network/DirectionsListener.java @@ -0,0 +1,8 @@ +package com.a1.nextlocation.network; + +import com.a1.nextlocation.data.Route; +import com.a1.nextlocation.json.DirectionsResult; + +public interface DirectionsListener { + void onDirectionsAvailable(DirectionsResult result); +} From 7b9ca656aa55fb1267a90a8991cf51f3c2b0ccc8 Mon Sep 17 00:00:00 2001 From: Bipin Date: Mon, 4 Jan 2021 11:49:14 +0100 Subject: [PATCH 04/21] Improved RouteTest, made LocationTest --- .../com/a1/nextlocation/LocationTest.java | 97 +++++++++++++++++++ .../java/com/a1/nextlocation/RouteTest.java | 25 +++-- 2 files changed, 113 insertions(+), 9 deletions(-) create mode 100644 app/src/test/java/com/a1/nextlocation/LocationTest.java diff --git a/app/src/test/java/com/a1/nextlocation/LocationTest.java b/app/src/test/java/com/a1/nextlocation/LocationTest.java new file mode 100644 index 0000000..5a3921f --- /dev/null +++ b/app/src/test/java/com/a1/nextlocation/LocationTest.java @@ -0,0 +1,97 @@ +package com.a1.nextlocation; + +import com.a1.nextlocation.data.Location; + +import org.junit.Before; +import org.junit.Test; +import org.osmdroid.util.GeoPoint; + +import static org.junit.Assert.*; + +public class LocationTest { + private Location testLocation; + @Before + public void init(){ + testLocation = new Location("testName", "15.4,27.5", "testDesc", null); + } + + @Test + public void nameTest(){ + String testName = "nameTestName"; + + String expectedBefore = "testName"; + String expectedAfter = "nameTestName"; + + assertEquals(expectedBefore, testLocation.getName()); + testLocation.setName(testName); + assertEquals(expectedAfter, testLocation.getName()); + } + + @Test + public void coordinatesTest(){ + String testCoordinaates = "32.4,15.7"; + + String expectedBefore = "15.4,27.5"; + String expectedAfter = "32.4,15.7"; + + assertEquals(expectedBefore, testLocation.getCoordinates()); + testLocation.setCoordinates(testCoordinaates); + assertEquals(expectedAfter, testLocation.getCoordinates()); + } + + @Test + public void descriptionTest(){ + String testDescription = "This description is a test!"; + + String expectedBefore = "testDesc"; + String expectedAfter = "This description is a test!"; + + assertEquals(expectedBefore, testLocation.getDescription()); + testLocation.setDescription(testDescription); + assertEquals(expectedAfter, testLocation.getDescription()); + } + + @Test + public void ImageURLTest(){ + String testURL = "https://i.imgur.com/FvohwaS.png"; + + String expectedBefore = null; + String expectedAfter = "https://i.imgur.com/FvohwaS.png"; + + assertEquals(expectedBefore ,testLocation.getImageUrl()); + testLocation.setImageUrl(testURL); + assertEquals(expectedAfter, testLocation.getImageUrl()); + } + + @Test + public void coordinateDoublesTest(){ + double[] testDoubles = new double[2]; + testDoubles[0] = 15.4; + testDoubles[1] = 27.5; + + double [] expectedCoordAsDouble = testDoubles; + String expectedStringFromDouble = "15.4,27.5"; + + assertArrayEquals(expectedCoordAsDouble, testLocation.getCoordinatesAsDoubles(), 0.1); + assertEquals(expectedStringFromDouble, testLocation.getStringFromCoordinates(testDoubles[0], testDoubles[1])); + } + + @Test + public void geoPointTest(){ + String testGeoPointCoords = "30.3,55.5"; + + GeoPoint expectedBefore = new GeoPoint(15.4, 27.5); + GeoPoint expectedAfter = new GeoPoint(30.3, 55.5); + + assertEquals(expectedBefore, testLocation.convertToGeoPoint()); + testLocation.setCoordinates(testGeoPointCoords); + assertEquals(expectedAfter, testLocation.convertToGeoPoint()); + } + + @Test + public void AlternateConstructorTest(){ + Location alternateTestLocation = new Location("testName", 15.4, 27.5, "testDesc", null); + + assertNotNull(alternateTestLocation); + } +} diff --git a/app/src/test/java/com/a1/nextlocation/RouteTest.java b/app/src/test/java/com/a1/nextlocation/RouteTest.java index 1d2dd3c..9b07a4e 100644 --- a/app/src/test/java/com/a1/nextlocation/RouteTest.java +++ b/app/src/test/java/com/a1/nextlocation/RouteTest.java @@ -3,6 +3,7 @@ package com.a1.nextlocation; import com.a1.nextlocation.data.Location; import com.a1.nextlocation.data.Route; +import org.junit.Before; import org.junit.Test; import java.util.ArrayList; @@ -11,17 +12,27 @@ import java.util.List; import static org.junit.Assert.*; public class RouteTest { + private Route route; + + @Before + public void init(){ + route = new Route("testName"); + } @Test - public void GetNameTest(){ - Route route = new Route("testName"); - String expected = "testName"; - assertEquals(expected, route.getName()); + public void nameTest(){ + String testName = "secondTestName"; + + String expectedBefore = "testName"; + String expectedAfter = "secondTestName"; + + assertEquals(expectedBefore, route.getName()); + route.setName(testName); + assertEquals(expectedAfter, route.getName()); } @Test public void getLocationsTest(){ - Route route = new Route("testName"); List expected = new ArrayList<>(); assertEquals(expected, route.getLocations()); @@ -29,7 +40,6 @@ public class RouteTest { @Test public void SetLocationsTest(){ - Route route = new Route("testName"); List testList = new ArrayList<>(); testList.add(new Location("name1", "coord1", "desc1", null)); testList.add(new Location("name2", "coord2", "desc2", null)); @@ -45,7 +55,6 @@ public class RouteTest { @Test public void AddLocationTest(){ - Route route = new Route("testName"); Location testLocation = new Location("testLocationName", "testCoordinates", "testDescription", null); List expectedBefore = new ArrayList<>(); @@ -59,7 +68,6 @@ public class RouteTest { @Test public void totalDistanceTest(){ - Route route = new Route("testName"); float testDistance = 523; float expectedBefore = 0; @@ -72,7 +80,6 @@ public class RouteTest { @Test public void totalTimeTest(){ - Route route = new Route("testName"); int testTime = 36; int expectedBefore = 0; From 96f32ccdbc44b45a079c8953cf84e964953dac64 Mon Sep 17 00:00:00 2001 From: Sem van der Hoeven Date: Mon, 4 Jan 2021 13:50:50 +0100 Subject: [PATCH 05/21] added deserialization of the api response --- app/build.gradle | 6 ++++ .../nextlocation/fragments/RouteFragment.java | 1 + .../nextlocation/json/DirectionsResult.java | 35 +++++++++++++++++-- .../a1/nextlocation/json/DirectionsStep.java | 32 +++++++++++++++++ 4 files changed, 72 insertions(+), 2 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index 9d6f2cc..84fdfce 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -26,6 +26,9 @@ android { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } + repositories { + maven { url "https://jitpack.io" } + } } dependencies { @@ -47,6 +50,9 @@ dependencies { //osm implementation 'org.osmdroid:osmdroid-android:6.1.8' + //osm bonus pack + implementation 'com.github.MKergall:osmbonuspack:6.6.0' + androidTestImplementation 'androidx.test.ext:junit:1.1.2' androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' } \ No newline at end of file diff --git a/app/src/main/java/com/a1/nextlocation/fragments/RouteFragment.java b/app/src/main/java/com/a1/nextlocation/fragments/RouteFragment.java index a415247..8e33968 100644 --- a/app/src/main/java/com/a1/nextlocation/fragments/RouteFragment.java +++ b/app/src/main/java/com/a1/nextlocation/fragments/RouteFragment.java @@ -42,5 +42,6 @@ public class RouteFragment extends Fragment { public void onDirectionsAvailable(DirectionsResult result) { Log.d(TAG, "onDirectionsAvailable: got result! " + result); + } } \ No newline at end of file diff --git a/app/src/main/java/com/a1/nextlocation/json/DirectionsResult.java b/app/src/main/java/com/a1/nextlocation/json/DirectionsResult.java index e52caba..0282174 100644 --- a/app/src/main/java/com/a1/nextlocation/json/DirectionsResult.java +++ b/app/src/main/java/com/a1/nextlocation/json/DirectionsResult.java @@ -1,5 +1,7 @@ package com.a1.nextlocation.json; +import android.util.Log; + import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; @@ -7,13 +9,18 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; +import org.osmdroid.util.GeoPoint; + +import java.lang.reflect.Array; import java.util.ArrayList; import java.util.List; public class DirectionsResult { + private static final String TAG = DirectionsResult.class.getCanonicalName(); private List steps = new ArrayList<>(); private double distance; private double duration; + private double[][] wayPointCoordinates; public List getSteps() { return steps; @@ -46,8 +53,21 @@ public class DirectionsResult { public void parse(String json) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); - JsonObject features = JsonParser.parseString(json).getAsJsonObject().get("features").getAsJsonArray().get(0).getAsJsonObject(); - JsonObject segment = features.get("properties").getAsJsonObject().getAsJsonArray("segments").get(0).getAsJsonObject(); + JsonObject feature = JsonParser.parseString(json).getAsJsonObject().get("features").getAsJsonArray().get(0).getAsJsonObject(); + JsonObject properties = feature.get("properties").getAsJsonObject(); + JsonArray wayPointCoordinates = feature.get("geometry").getAsJsonObject().getAsJsonArray("coordinates"); + this.wayPointCoordinates = new double[wayPointCoordinates.size()][2]; + + + for (int i = 0; i < wayPointCoordinates.size(); i++) { + JsonElement j = wayPointCoordinates.get(i); + JsonArray arr = j.getAsJsonArray(); + this.wayPointCoordinates[i][0] = arr.get(0).getAsDouble(); + this.wayPointCoordinates[i][1] = arr.get(1).getAsDouble(); + } + + + JsonObject segment = properties.getAsJsonArray("segments").get(0).getAsJsonObject(); setDistance(segment.get("distance").getAsDouble()); setDuration(segment.get("duration").getAsDouble()); @@ -56,7 +76,18 @@ public class DirectionsResult { for (JsonElement j : steps) { DirectionsStep step = gson.fromJson(j,DirectionsStep.class); + double lat; + double longl; + for (int i = 0; i < 2; i++) { + lat = this.wayPointCoordinates[step.getWay_points().get(i)][0]; + longl = this.wayPointCoordinates[step.getWay_points().get(i)][1]; + step.getWaypoints()[i] = new GeoPoint(lat,longl); + } + addStep(step); + Log.d(TAG, "parse: added step" + step); } + + } } diff --git a/app/src/main/java/com/a1/nextlocation/json/DirectionsStep.java b/app/src/main/java/com/a1/nextlocation/json/DirectionsStep.java index 64678f8..c495cef 100644 --- a/app/src/main/java/com/a1/nextlocation/json/DirectionsStep.java +++ b/app/src/main/java/com/a1/nextlocation/json/DirectionsStep.java @@ -1,10 +1,26 @@ package com.a1.nextlocation.json; +import org.osmdroid.util.GeoPoint; + +import java.util.ArrayList; + +/** + * pojo class that holds the step object from the api response + */ public class DirectionsStep { private double distance; private double duration; private String instruction; private String name; + /** + * these are the actual waypoints that the step refers to. The first is the beginning of the step, and the second is what it leads to. + * The second geopoint is always the first geopoint of the next step in the list of the {@link DirectionsResult} object. + */ + private GeoPoint[] waypoints = new GeoPoint[2]; + /** + * this is a list of the waypoints that are in the response, it is called way_points so it can be automatically serialized with gson + */ + private ArrayList way_points; public double getDistance() { return distance; @@ -37,4 +53,20 @@ public class DirectionsStep { public void setName(String name) { this.name = name; } + + public ArrayList getWay_points() { + return way_points; + } + + public void setWay_points(ArrayList way_points) { + this.way_points = way_points; + } + + public GeoPoint[] getWaypoints() { + return waypoints; + } + + public void setWaypoints(GeoPoint[] waypoints) { + this.waypoints = waypoints; + } } From 5e218f3b9991aace947c0d2a666b2ead07d48b87 Mon Sep 17 00:00:00 2001 From: Sem van der Hoeven Date: Mon, 4 Jan 2021 15:20:24 +0100 Subject: [PATCH 06/21] added getting directions for whole route --- .../nextlocation/fragments/RouteFragment.java | 10 +- .../nextlocation/json/DirectionsResult.java | 99 ++++++++++++++++--- .../a1/nextlocation/json/GeometryDecoder.java | 63 ++++++++++++ .../a1/nextlocation/network/ApiHandler.java | 52 ++++++++++ 4 files changed, 209 insertions(+), 15 deletions(-) create mode 100644 app/src/main/java/com/a1/nextlocation/json/GeometryDecoder.java diff --git a/app/src/main/java/com/a1/nextlocation/fragments/RouteFragment.java b/app/src/main/java/com/a1/nextlocation/fragments/RouteFragment.java index 8e33968..d61a62a 100644 --- a/app/src/main/java/com/a1/nextlocation/fragments/RouteFragment.java +++ b/app/src/main/java/com/a1/nextlocation/fragments/RouteFragment.java @@ -12,6 +12,8 @@ import android.view.View; import android.view.ViewGroup; import com.a1.nextlocation.R; +import com.a1.nextlocation.data.Location; +import com.a1.nextlocation.data.Route; import com.a1.nextlocation.json.DirectionsResult; import com.a1.nextlocation.network.ApiHandler; import com.a1.nextlocation.network.DirectionsListener; @@ -37,11 +39,17 @@ public class RouteFragment extends Fragment { public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); - ApiHandler.INSTANCE.getDirections(8.681436,49.41461,8.687872,49.420318); +// ApiHandler.INSTANCE.getDirections(8.681436,49.41461,8.687872,49.420318); + Route r = new Route("test"); + r.addLocation(new Location("test",8.681436,49.41461,"route",null)); + r.addLocation(new Location("test",8.687872,49.420318,"route",null)); + ApiHandler.INSTANCE.getDirections(r); } public void onDirectionsAvailable(DirectionsResult result) { Log.d(TAG, "onDirectionsAvailable: got result! " + result); + + } } \ No newline at end of file diff --git a/app/src/main/java/com/a1/nextlocation/json/DirectionsResult.java b/app/src/main/java/com/a1/nextlocation/json/DirectionsResult.java index 0282174..8cf1c7c 100644 --- a/app/src/main/java/com/a1/nextlocation/json/DirectionsResult.java +++ b/app/src/main/java/com/a1/nextlocation/json/DirectionsResult.java @@ -8,7 +8,9 @@ import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; +import com.google.gson.JsonPrimitive; +import org.json.JSONArray; import org.osmdroid.util.GeoPoint; import java.lang.reflect.Array; @@ -50,6 +52,10 @@ public class DirectionsResult { this.steps.add(step); } + /** + * parses a given json string into this object. It gets all the waypoints and steps and combines them so that every step also has the correct coordinates associated with it + * @param json the json string to parse. + */ public void parse(String json) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); @@ -59,6 +65,7 @@ public class DirectionsResult { this.wayPointCoordinates = new double[wayPointCoordinates.size()][2]; + // fill the way point coordinates list for later use for (int i = 0; i < wayPointCoordinates.size(); i++) { JsonElement j = wayPointCoordinates.get(i); JsonArray arr = j.getAsJsonArray(); @@ -67,27 +74,91 @@ public class DirectionsResult { } - JsonObject segment = properties.getAsJsonArray("segments").get(0).getAsJsonObject(); + JsonArray segments = properties.getAsJsonArray("segments"); - setDistance(segment.get("distance").getAsDouble()); - setDuration(segment.get("duration").getAsDouble()); + for (JsonElement element : segments) { + JsonObject segment = element.getAsJsonObject(); - JsonArray steps = segment.getAsJsonArray("steps"); + setDistance(segment.get("distance").getAsDouble()); + setDuration(segment.get("duration").getAsDouble()); - for (JsonElement j : steps) { - DirectionsStep step = gson.fromJson(j,DirectionsStep.class); - double lat; - double longl; - for (int i = 0; i < 2; i++) { - lat = this.wayPointCoordinates[step.getWay_points().get(i)][0]; - longl = this.wayPointCoordinates[step.getWay_points().get(i)][1]; - step.getWaypoints()[i] = new GeoPoint(lat,longl); + JsonArray steps = segment.getAsJsonArray("steps"); + + for (JsonElement j : steps) { + + DirectionsStep step = gson.fromJson(j,DirectionsStep.class); + double lat; + double longl; + + // kinda stinky but it works + for (int i = 0; i < 2; i++) { + lat = this.wayPointCoordinates[step.getWay_points().get(i)][0]; + longl = this.wayPointCoordinates[step.getWay_points().get(i)][1]; + step.getWaypoints()[i] = new GeoPoint(lat,longl); + } + + addStep(step); + Log.d(TAG, "parse: added step" + step); + } + } + + } + + public void parseRoute(String json) { + + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + JsonArray routes = JsonParser.parseString(json).getAsJsonObject().getAsJsonArray("routes"); + for (JsonElement element : routes) { + JsonObject route = element.getAsJsonObject(); + JsonObject summary = route.getAsJsonObject("summary"); + this.distance = summary.get("distance").getAsDouble(); + this.duration = summary.get("duration").getAsDouble(); + + JsonPrimitive geometry = route.getAsJsonPrimitive("geometry"); + JsonArray wayPointCoordinates = GeometryDecoder.decodeGeometry(geometry.getAsString(),false); + this.wayPointCoordinates = new double[wayPointCoordinates.size()][2]; + + + // fill the way point coordinates list for later use + for (int i = 0; i < wayPointCoordinates.size(); i++) { + JsonElement j = wayPointCoordinates.get(i); + JsonArray arr = j.getAsJsonArray(); + this.wayPointCoordinates[i][0] = arr.get(0).getAsDouble(); + this.wayPointCoordinates[i][1] = arr.get(1).getAsDouble(); + } + + + JsonArray segments = route.getAsJsonArray("segments"); + + for (JsonElement e : segments) { + JsonObject segment = e.getAsJsonObject(); + + setDistance(segment.get("distance").getAsDouble()); + setDuration(segment.get("duration").getAsDouble()); + + JsonArray steps = segment.getAsJsonArray("steps"); + + for (JsonElement j : steps) { + + DirectionsStep step = gson.fromJson(j,DirectionsStep.class); + double lat; + double longl; + + // kinda stinky but it works + for (int i = 0; i < 2; i++) { + lat = this.wayPointCoordinates[step.getWay_points().get(i)][0]; + longl = this.wayPointCoordinates[step.getWay_points().get(i)][1]; + step.getWaypoints()[i] = new GeoPoint(lat,longl); + } + + addStep(step); + Log.d(TAG, "parse: added step" + step); + } } - addStep(step); - Log.d(TAG, "parse: added step" + step); } + } } diff --git a/app/src/main/java/com/a1/nextlocation/json/GeometryDecoder.java b/app/src/main/java/com/a1/nextlocation/json/GeometryDecoder.java new file mode 100644 index 0000000..3884e52 --- /dev/null +++ b/app/src/main/java/com/a1/nextlocation/json/GeometryDecoder.java @@ -0,0 +1,63 @@ +package com.a1.nextlocation.json; + +import com.google.gson.JsonArray; + +import org.json.JSONArray; +import org.json.JSONException; + +/** + * source: https://github.com/GIScience/openrouteservice-docs#geometry-decoding + */ +public class GeometryDecoder { + + public static JsonArray decodeGeometry(String encodedGeometry, boolean inclElevation) { + JsonArray geometry = new JsonArray(); + int len = encodedGeometry.length(); + int index = 0; + int lat = 0; + int lng = 0; + int ele = 0; + + while (index < len) { + int result = 1; + int shift = 0; + int b; + do { + b = encodedGeometry.charAt(index++) - 63 - 1; + result += b << shift; + shift += 5; + } while (b >= 0x1f); + lat += (result & 1) != 0 ? ~(result >> 1) : (result >> 1); + + result = 1; + shift = 0; + do { + b = encodedGeometry.charAt(index++) - 63 - 1; + result += b << shift; + shift += 5; + } while (b >= 0x1f); + lng += (result & 1) != 0 ? ~(result >> 1) : (result >> 1); + + + if(inclElevation){ + result = 1; + shift = 0; + do { + b = encodedGeometry.charAt(index++) - 63 - 1; + result += b << shift; + shift += 5; + } while (b >= 0x1f); + ele += (result & 1) != 0 ? ~(result >> 1) : (result >> 1); + } + + JsonArray location = new JsonArray(); + location.add(lat / 1E5); + location.add(lng / 1E5); + if(inclElevation){ + location.add((float) (ele / 100)); + } + geometry.add(location); + } + return geometry; + } +} \ No newline at end of file diff --git a/app/src/main/java/com/a1/nextlocation/network/ApiHandler.java b/app/src/main/java/com/a1/nextlocation/network/ApiHandler.java index 0bf76dc..1b480a8 100644 --- a/app/src/main/java/com/a1/nextlocation/network/ApiHandler.java +++ b/app/src/main/java/com/a1/nextlocation/network/ApiHandler.java @@ -5,6 +5,8 @@ import android.util.Log; import com.a1.nextlocation.data.Location; import com.a1.nextlocation.data.Route; import com.a1.nextlocation.json.DirectionsResult; +import com.google.gson.Gson; +import com.google.gson.JsonObject; import java.io.IOException; import java.util.ArrayList; @@ -15,6 +17,7 @@ import java.util.concurrent.atomic.AtomicReference; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; +import okhttp3.RequestBody; import okhttp3.Response; public enum ApiHandler { @@ -72,6 +75,55 @@ public enum ApiHandler { this.listeners.add(listener); } + public void getDirections(Route route) { +// for (int i = 0; i < route.getLocations().size()-1; i+= 2) { +// Location start = route.getLocations().get(i); +// Location end = route.getLocations().get(i+1); +// getDirections(start,end); +// } + + ArrayList allCoords = new ArrayList<>(); + for (Location location : route.getLocations()) { + allCoords.add(location.getCoordinatesAsDoubles()); + } + + String body = "{\"coordinates\":" + new Gson().toJson(allCoords) + "}"; + + + String requestUrl = BASE_URL + DIRECTIONS_MODE + "?api_key=" + API_KEY; + + Thread t = new Thread(() -> { + + RequestBody requestBody = RequestBody.create(body,JSON); + Request request = new Request.Builder() + .url(requestUrl) + .post(requestBody) + .build(); + + try (Response response = client.newCall(request).execute()) { + if (response.body() != null) { + String responseString = Objects.requireNonNull(response.body()).string(); + Log.d(TAG, "getDirections: got response: " + responseString); + + DirectionsResult result = new DirectionsResult(); + result.parseRoute(responseString); + Log.d(TAG, "getDirections: " + result.getSteps().size()); + + for (DirectionsListener listener : listeners) { + listener.onDirectionsAvailable(result); + } + } + + } catch (IOException e) { + Log.d(TAG, "getDirections: caught exception: " + e.getLocalizedMessage()); + } + }); + + t.start(); + + + } + From da45a0a40eb8c03c699c1e0bf7df2b5cdd0bf768 Mon Sep 17 00:00:00 2001 From: Robin Koedood Date: Mon, 4 Jan 2021 15:27:52 +0100 Subject: [PATCH 07/21] [TRIED] Test FileIO class No luck so far --- app/build.gradle | 1 + app/src/main/AndroidManifest.xml | 2 + .../com/a1/nextlocation/MainActivity.java | 15 +++++ .../java/com/a1/nextlocation/data/FileIO.java | 53 ++++++++++++++++- .../java/com/a1/nextlocation/FileIOTest.java | 57 +++++++++++++++++++ 5 files changed, 125 insertions(+), 3 deletions(-) create mode 100644 app/src/test/java/com/a1/nextlocation/FileIOTest.java diff --git a/app/build.gradle b/app/build.gradle index 9d6f2cc..19d1ad6 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -49,4 +49,5 @@ dependencies { androidTestImplementation 'androidx.test.ext:junit:1.1.2' androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' + testImplementation 'org.mockito:mockito-core:2.7.22' } \ No newline at end of file diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index f5def4b..d82a8f3 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -6,6 +6,8 @@ + + fileIO = new FileIO<>(); + fileIO.writeFileData(new Route("TERSTSET"), getApplicationContext()); + Log.d(TAG, "onCreate: " + "FILE GESCHREVENN!!!!!");*/ + LocationListManager.INSTANCE.setContext(this); LocationListManager.INSTANCE.load(); CouponListManager.INSTANCE.setContext(this); diff --git a/app/src/main/java/com/a1/nextlocation/data/FileIO.java b/app/src/main/java/com/a1/nextlocation/data/FileIO.java index a47f76e..33fd03e 100644 --- a/app/src/main/java/com/a1/nextlocation/data/FileIO.java +++ b/app/src/main/java/com/a1/nextlocation/data/FileIO.java @@ -2,17 +2,26 @@ package com.a1.nextlocation.data; import android.content.Context; import android.content.res.AssetManager; +import android.os.Environment; import android.util.Log; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; +import org.json.JSONArray; + import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.lang.reflect.Type; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; @@ -50,7 +59,45 @@ public class FileIO { return res; } - public void writeFileData(T objectToWrite) { - //TODO make - } +// public void writeFileData(T objectToWrite, Context context) { +// //TODO make +// //object naar jsonobject +// //jsonarray toevoegen/maken +// //filewriter naar file +// +// String filename = ""; +// if (objectToWrite instanceof Coupon){ +// filename = "coupons.json"; +// } +// +// if (objectToWrite instanceof Route){ +// filename = "routes.json"; +// } +// +// if (objectToWrite instanceof Location){ +// filename = "locations.json"; +// } +// +// try (FileOutputStream fileOutputStream = context.openFileOutput(filename, Context.MODE_PRIVATE)){ +// String json = new Gson().toJson(objectToWrite); +// +// fileOutputStream.write(json.getBytes(StandardCharsets.UTF_8)); +// +// } catch (FileNotFoundException e) { +// e.printStackTrace(); +// } catch (IOException e) { +// e.printStackTrace(); +// } +// +// /*try (FileWriter fileWriter = new FileWriter(filename)){ +// +// String json = new Gson().toJson(objectToWrite); +// +// fileWriter.append(json); +// fileWriter.flush(); +// +// } catch (IOException e) { +// e.printStackTrace(); +// }*/ +// } } diff --git a/app/src/test/java/com/a1/nextlocation/FileIOTest.java b/app/src/test/java/com/a1/nextlocation/FileIOTest.java new file mode 100644 index 0000000..1f2894f --- /dev/null +++ b/app/src/test/java/com/a1/nextlocation/FileIOTest.java @@ -0,0 +1,57 @@ +package com.a1.nextlocation; + +import android.app.Instrumentation; +import android.content.Context; +import android.content.pm.InstrumentationInfo; +import android.widget.ArrayAdapter; + +import com.a1.nextlocation.data.FileIO; +import com.a1.nextlocation.data.Location; +import com.a1.nextlocation.data.Route; +import com.google.gson.reflect.TypeToken; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.mockito.Mock; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; + +public class FileIOTest { + +// @Test +// public void testReadFileIO() { +// //System.out.println(Arrays.toString(mMockContext.fileList())); +// Context mMockContext = mock(MainActivity.class); +// List expected = new ArrayList<>(); +// Route testRoute = new Route("rondje stad"); +// testRoute.addLocation(new Location("kees kroket", "2.4654645,6.2342323", "lekkere patatjes", null)); +// testRoute.setTotalDistance(2.3434f); +// testRoute.setTotalTime(342342); +// expected.add(testRoute); +// +// /* +// FileIO> fileIO = new FileIO<>(); +// ArrayList res = fileIO.readFileData(context, "routes.json",new TypeToken>(){}.getType()); +// */ +// +// if (mMockContext.getAssets() == null) +// System.out.println("daar ga je"); +// +// FileIO> fileIO = new FileIO<>(); +// ArrayList res = fileIO.readFileData(mMockContext, "routes.json", new TypeToken>(){}.getType()); +// +// assertEquals(expected, res); +// +// } + +} From 9b93ddaec5149324e98c5abb2f0dec10f43aae4d Mon Sep 17 00:00:00 2001 From: Sem van der Hoeven Date: Mon, 4 Jan 2021 15:44:47 +0100 Subject: [PATCH 08/21] stuff --- .../java/com/a1/nextlocation/fragments/RouteFragment.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/com/a1/nextlocation/fragments/RouteFragment.java b/app/src/main/java/com/a1/nextlocation/fragments/RouteFragment.java index d61a62a..3ebe08a 100644 --- a/app/src/main/java/com/a1/nextlocation/fragments/RouteFragment.java +++ b/app/src/main/java/com/a1/nextlocation/fragments/RouteFragment.java @@ -48,8 +48,7 @@ public class RouteFragment extends Fragment { public void onDirectionsAvailable(DirectionsResult result) { Log.d(TAG, "onDirectionsAvailable: got result! " + result); - - - + + } } \ No newline at end of file From e8af38981f40af4f5d528613e77073c00a4818a1 Mon Sep 17 00:00:00 2001 From: Sem van der Hoeven Date: Tue, 5 Jan 2021 11:25:13 +0100 Subject: [PATCH 09/21] added visualizing route --- .../a1/nextlocation/data/CurrentRoute.java | 18 ++++++ .../com/a1/nextlocation/data/Location.java | 2 +- .../nextlocation/fragments/HomeFragment.java | 64 ++++++++++++++++--- .../nextlocation/fragments/RouteFragment.java | 22 +++---- .../nextlocation/json/DirectionsResult.java | 40 ++++++++++-- .../a1/nextlocation/network/ApiHandler.java | 18 +++++- app/src/main/res/values/colors.xml | 1 + 7 files changed, 134 insertions(+), 31 deletions(-) create mode 100644 app/src/main/java/com/a1/nextlocation/data/CurrentRoute.java diff --git a/app/src/main/java/com/a1/nextlocation/data/CurrentRoute.java b/app/src/main/java/com/a1/nextlocation/data/CurrentRoute.java new file mode 100644 index 0000000..a0642f0 --- /dev/null +++ b/app/src/main/java/com/a1/nextlocation/data/CurrentRoute.java @@ -0,0 +1,18 @@ +package com.a1.nextlocation.data; + +import org.osmdroid.views.overlay.Polyline; + +public enum CurrentRoute { + INSTANCE; + + private Polyline currentRoute; + + public void setCurrentRoute(Polyline currentRoute) { + this.currentRoute = currentRoute; + } + + public Polyline getCurrentRoute() { + return currentRoute; + } + +} diff --git a/app/src/main/java/com/a1/nextlocation/data/Location.java b/app/src/main/java/com/a1/nextlocation/data/Location.java index f7d2362..e0eb89d 100644 --- a/app/src/main/java/com/a1/nextlocation/data/Location.java +++ b/app/src/main/java/com/a1/nextlocation/data/Location.java @@ -105,7 +105,7 @@ public class Location implements Parcelable { } public static String getStringFromCoordinates(double lat1, double long1) { - return lat1 + "," + long1; + return long1 + "," + lat1; } public GeoPoint convertToGeoPoint() { diff --git a/app/src/main/java/com/a1/nextlocation/fragments/HomeFragment.java b/app/src/main/java/com/a1/nextlocation/fragments/HomeFragment.java index 621d02b..e6dcd75 100644 --- a/app/src/main/java/com/a1/nextlocation/fragments/HomeFragment.java +++ b/app/src/main/java/com/a1/nextlocation/fragments/HomeFragment.java @@ -23,31 +23,45 @@ import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import com.a1.nextlocation.R; +import com.a1.nextlocation.data.CurrentRoute; import com.a1.nextlocation.data.Route; +import com.a1.nextlocation.json.DirectionsResult; +import com.a1.nextlocation.network.ApiHandler; import com.a1.nextlocation.recyclerview.CouponListManager; import com.a1.nextlocation.recyclerview.CustomOverlay; import com.a1.nextlocation.recyclerview.LocationListManager; import com.a1.nextlocation.recyclerview.RouteListManager; import org.osmdroid.api.IMapController; +import org.osmdroid.bonuspack.routing.MapQuestRoadManager; +import org.osmdroid.bonuspack.routing.OSRMRoadManager; +import org.osmdroid.bonuspack.routing.Road; +import org.osmdroid.bonuspack.routing.RoadManager; import org.osmdroid.config.Configuration; import org.osmdroid.util.GeoPoint; import org.osmdroid.views.MapView; import org.osmdroid.views.overlay.Overlay; import org.osmdroid.views.overlay.OverlayItem; +import org.osmdroid.views.overlay.Polyline; import org.osmdroid.views.overlay.compass.CompassOverlay; import org.osmdroid.views.overlay.compass.InternalCompassOrientationProvider; import org.osmdroid.views.overlay.mylocation.GpsMyLocationProvider; import org.osmdroid.views.overlay.mylocation.MyLocationNewOverlay; import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; public class HomeFragment extends Fragment { private final String userAgent = "com.ai.nextlocation.fragments"; + public final static String MAPQUEST_API_KEY = "vuyXjqnAADpjeL9QwtgWGleIk95e36My"; private ImageButton imageButton; private MapView mapView; private final int REQUEST_PERMISSIONS_REQUEST_CODE = 1; private final String TAG = HomeFragment.class.getCanonicalName(); + private RoadManager roadManager; + private Polyline roadOverlay; @Override public void onCreate(Bundle savedInstanceState) { @@ -57,6 +71,7 @@ public class HomeFragment extends Fragment { Manifest.permission.ACCESS_FINE_LOCATION, // WRITE_EXTERNAL_STORAGE is required in order to show the map Manifest.permission.WRITE_EXTERNAL_STORAGE); + roadManager = new OSRMRoadManager(requireContext()); } @@ -72,9 +87,25 @@ public class HomeFragment extends Fragment { ((FragmentActivity) view.getContext()).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_layout, locationFragment).addToBackStack(null).commit(); }); + +// roadManager.addRequestOption("routeType=foot-walking"); + ApiHandler.INSTANCE.addListener(this::onDirectionsAvailable); return view; } + private void onDirectionsAvailable(DirectionsResult directionsResult) { + Log.d(TAG, "onDirectionsAvailable: got result! " + directionsResult); + ArrayList geoPoints = directionsResult.getGeoPoints(); + roadOverlay = new Polyline(); + roadOverlay.setPoints(geoPoints); + roadOverlay.setColor(R.color.red); + + + CurrentRoute.INSTANCE.setCurrentRoute(roadOverlay); + Log.d(TAG, "onDirectionsAvailable: successfully added road!"); + + } + @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); @@ -106,18 +137,18 @@ public class HomeFragment extends Fragment { mLocationOverlay.enableMyLocation(); mapView.getOverlays().add(mLocationOverlay); - CustomOverlay customOverlay = new CustomOverlay(getResources().getDrawable(R.drawable.ic_baseline_location_on_24),mapView); - - for (com.a1.nextlocation.data.Location l : LocationListManager.INSTANCE.getLocationList()) { - GeoPoint p = new GeoPoint(l.getLat(), l.getLong()); - OverlayItem overlayItem = new OverlayItem(l.getName(),l.getDescription(), p); - - customOverlay.addOverlayItem(overlayItem); - Log.d(TAG, "initMap: " + "succes"); - } +// CustomOverlay customOverlay = new CustomOverlay(getResources().getDrawable(R.drawable.ic_baseline_location_on_24),mapView); +// +// for (com.a1.nextlocation.data.Location l : LocationListManager.INSTANCE.getLocationList()) { +// GeoPoint p = new GeoPoint(l.getLat(), l.getLong()); +// OverlayItem overlayItem = new OverlayItem(l.getName(),l.getDescription(), p); +// +// customOverlay.addOverlayItem(overlayItem); +// Log.d(TAG, "initMap: " + "succes"); +// } - mapView.getOverlays().add(customOverlay); +// mapView.getOverlays().add(customOverlay); // add the zoom controller IMapController mapController = mapView.getController(); @@ -143,6 +174,19 @@ public class HomeFragment extends Fragment { } + if (roadOverlay == null) { + if (CurrentRoute.INSTANCE.getCurrentRoute() != null) { + roadOverlay = CurrentRoute.INSTANCE.getCurrentRoute(); + mapView.getOverlays().add(roadOverlay); + mapView.invalidate(); + Log.d(TAG, "initMap: successfully added road!"); + } + } else { + mapView.getOverlays().add(roadOverlay); + mapView.invalidate(); + Log.d(TAG, "initMap: successfully added road!"); + } + } private void requestPermissionsIfNecessary(String... permissions) { ArrayList permissionsToRequest = new ArrayList<>(); diff --git a/app/src/main/java/com/a1/nextlocation/fragments/RouteFragment.java b/app/src/main/java/com/a1/nextlocation/fragments/RouteFragment.java index 752b7d6..85d8c02 100644 --- a/app/src/main/java/com/a1/nextlocation/fragments/RouteFragment.java +++ b/app/src/main/java/com/a1/nextlocation/fragments/RouteFragment.java @@ -38,7 +38,6 @@ public class RouteFragment extends Fragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - ApiHandler.INSTANCE.addListener(this::onDirectionsAvailable); } @@ -71,16 +70,15 @@ public class RouteFragment extends Fragment { public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); -// ApiHandler.INSTANCE.getDirections(8.681436,49.41461,8.687872,49.420318); -// Route r = new Route("test"); -// r.addLocation(new Location("test",8.681436,49.41461,"route",null)); -// r.addLocation(new Location("test",8.687872,49.420318,"route",null)); -// ApiHandler.INSTANCE.getDirections(r); - } - - public void onDirectionsAvailable(DirectionsResult result) { - Log.d(TAG, "onDirectionsAvailable: got result! " + result); - - + ApiHandler.INSTANCE.getDirections(51.49017262451581, 4.289038164073164,51.47337383133509, 4.303535222390562); + Route r = new Route("test"); + r.addLocation(new Location("test",51.487963606716185, 4.280396603442448,"route",null)); + r.addLocation(new Location("test",51.486962126272886, 4.27884897122147,"route",null)); + r.addLocation(new Location("test",51.485412622620224, 4.277392376189963,"route",null)); + r.addLocation(new Location("test",51.4801212376542, 4.281610432511638,"route",null)); + r.addLocation(new Location("test",51.481103969835665, 4.2903500027691805,"route",null)); +// r.addLocation(new Location("test",51.489063681658145, 4.289596063527951,"route",null)); +// r.addLocation(new Location("test",51.483012677667766, 4.28003245468457,"route",null)); + ApiHandler.INSTANCE.getDirections(r); } } \ No newline at end of file diff --git a/app/src/main/java/com/a1/nextlocation/json/DirectionsResult.java b/app/src/main/java/com/a1/nextlocation/json/DirectionsResult.java index 8cf1c7c..7f52783 100644 --- a/app/src/main/java/com/a1/nextlocation/json/DirectionsResult.java +++ b/app/src/main/java/com/a1/nextlocation/json/DirectionsResult.java @@ -15,6 +15,7 @@ import org.osmdroid.util.GeoPoint; import java.lang.reflect.Array; import java.util.ArrayList; +import java.util.Collections; import java.util.List; public class DirectionsResult { @@ -23,6 +24,7 @@ public class DirectionsResult { private double distance; private double duration; private double[][] wayPointCoordinates; + private GeoPoint[] startAndEndPoint = new GeoPoint[2]; public List getSteps() { return steps; @@ -52,8 +54,31 @@ public class DirectionsResult { this.steps.add(step); } + public GeoPoint[] getStartAndEndPoint() { + return startAndEndPoint; + } + + /** + * converts all the geopoints in all the steps into an arraylist to display it on the map + * @return the list of geopoints + */ + public ArrayList getGeoPoints() { + int size = 0; + // we'll have a lot of waypoints, so calculate the size first so that the list won't have to be extended (o p t i m i z e) + for (int i = 0; i < this.getSteps().size(); i++) { + size += this.getSteps().get(i).getWaypoints().length; + } + + ArrayList res = new ArrayList<>(size); + for (DirectionsStep step : this.getSteps()) { + Collections.addAll(res, step.getWaypoints()); + } + return res; + } + /** * parses a given json string into this object. It gets all the waypoints and steps and combines them so that every step also has the correct coordinates associated with it + * * @param json the json string to parse. */ public void parse(String json) { @@ -86,7 +111,7 @@ public class DirectionsResult { for (JsonElement j : steps) { - DirectionsStep step = gson.fromJson(j,DirectionsStep.class); + DirectionsStep step = gson.fromJson(j, DirectionsStep.class); double lat; double longl; @@ -94,7 +119,7 @@ public class DirectionsResult { for (int i = 0; i < 2; i++) { lat = this.wayPointCoordinates[step.getWay_points().get(i)][0]; longl = this.wayPointCoordinates[step.getWay_points().get(i)][1]; - step.getWaypoints()[i] = new GeoPoint(lat,longl); + step.getWaypoints()[i] = new GeoPoint(lat, longl); } addStep(step); @@ -102,6 +127,9 @@ public class DirectionsResult { } } + startAndEndPoint[0] = this.getSteps().get(0).getWaypoints()[0]; + startAndEndPoint[1] = this.getSteps().get(this.getSteps().size()-1).getWaypoints()[1]; + } public void parseRoute(String json) { @@ -115,7 +143,7 @@ public class DirectionsResult { this.duration = summary.get("duration").getAsDouble(); JsonPrimitive geometry = route.getAsJsonPrimitive("geometry"); - JsonArray wayPointCoordinates = GeometryDecoder.decodeGeometry(geometry.getAsString(),false); + JsonArray wayPointCoordinates = GeometryDecoder.decodeGeometry(geometry.getAsString(), false); this.wayPointCoordinates = new double[wayPointCoordinates.size()][2]; @@ -140,7 +168,7 @@ public class DirectionsResult { for (JsonElement j : steps) { - DirectionsStep step = gson.fromJson(j,DirectionsStep.class); + DirectionsStep step = gson.fromJson(j, DirectionsStep.class); double lat; double longl; @@ -148,7 +176,7 @@ public class DirectionsResult { for (int i = 0; i < 2; i++) { lat = this.wayPointCoordinates[step.getWay_points().get(i)][0]; longl = this.wayPointCoordinates[step.getWay_points().get(i)][1]; - step.getWaypoints()[i] = new GeoPoint(lat,longl); + step.getWaypoints()[i] = new GeoPoint(lat, longl); } addStep(step); @@ -158,7 +186,5 @@ public class DirectionsResult { } - - } } diff --git a/app/src/main/java/com/a1/nextlocation/network/ApiHandler.java b/app/src/main/java/com/a1/nextlocation/network/ApiHandler.java index 1b480a8..5787b30 100644 --- a/app/src/main/java/com/a1/nextlocation/network/ApiHandler.java +++ b/app/src/main/java/com/a1/nextlocation/network/ApiHandler.java @@ -38,7 +38,7 @@ public enum ApiHandler { } public void getDirections(double startLat, double startLong, double endLat, double endLong) { - getDirections(startLat + "," + startLong, endLat + "," + endLong); + getDirections(startLong + "," + startLat, endLong + "," + endLat); } public void getDirections(String startLocation, String endLocation) { @@ -69,6 +69,12 @@ public enum ApiHandler { t.start(); +// try { +// t.join(); +// } catch (InterruptedException e) { +// e.printStackTrace(); +// } + } public void addListener(DirectionsListener listener) { @@ -104,6 +110,10 @@ public enum ApiHandler { if (response.body() != null) { String responseString = Objects.requireNonNull(response.body()).string(); Log.d(TAG, "getDirections: got response: " + responseString); + if (responseString.startsWith("{\"error")) { + Log.e(TAG, "getDirections: ERROR IN REQUEST!"); + return; + } DirectionsResult result = new DirectionsResult(); result.parseRoute(responseString); @@ -121,6 +131,12 @@ public enum ApiHandler { t.start(); +// try { +// t.join(); +// } catch (InterruptedException e) { +// e.printStackTrace(); +// } + } diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml index cf6f6b1..a8f6080 100644 --- a/app/src/main/res/values/colors.xml +++ b/app/src/main/res/values/colors.xml @@ -10,4 +10,5 @@ #FF115571 #FF31AFB4 #FF14212D + #FF0000 \ No newline at end of file From f5f077db0ff6b515ee05785ac5eae58b72ad10c3 Mon Sep 17 00:00:00 2001 From: Sem van der Hoeven Date: Tue, 5 Jan 2021 12:13:42 +0100 Subject: [PATCH 10/21] location stuff --- .../nextlocation/fragments/HomeFragment.java | 65 ++++++++++++++----- .../nextlocation/fragments/RouteFragment.java | 13 ++-- .../a1/nextlocation/network/ApiHandler.java | 10 +-- 3 files changed, 59 insertions(+), 29 deletions(-) diff --git a/app/src/main/java/com/a1/nextlocation/fragments/HomeFragment.java b/app/src/main/java/com/a1/nextlocation/fragments/HomeFragment.java index e6dcd75..516db24 100644 --- a/app/src/main/java/com/a1/nextlocation/fragments/HomeFragment.java +++ b/app/src/main/java/com/a1/nextlocation/fragments/HomeFragment.java @@ -7,6 +7,7 @@ import android.content.Context; import android.content.pm.PackageManager; import android.content.res.Resources; import android.location.Location; +import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.util.Log; @@ -53,7 +54,7 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; -public class HomeFragment extends Fragment { +public class HomeFragment extends Fragment implements LocationListener { private final String userAgent = "com.ai.nextlocation.fragments"; public final static String MAPQUEST_API_KEY = "vuyXjqnAADpjeL9QwtgWGleIk95e36My"; private ImageButton imageButton; @@ -62,6 +63,9 @@ public class HomeFragment extends Fragment { private final String TAG = HomeFragment.class.getCanonicalName(); private RoadManager roadManager; private Polyline roadOverlay; + private int color; + + private GeoPoint currentLocation; @Override public void onCreate(Bundle savedInstanceState) { @@ -71,8 +75,10 @@ public class HomeFragment extends Fragment { Manifest.permission.ACCESS_FINE_LOCATION, // WRITE_EXTERNAL_STORAGE is required in order to show the map Manifest.permission.WRITE_EXTERNAL_STORAGE); - roadManager = new OSRMRoadManager(requireContext()); + roadManager = new MapQuestRoadManager(MAPQUEST_API_KEY); + roadManager.addRequestOption("routeType=foot-walking"); + color = requireContext().getColor(R.color.red); } @Override @@ -98,7 +104,14 @@ public class HomeFragment extends Fragment { ArrayList geoPoints = directionsResult.getGeoPoints(); roadOverlay = new Polyline(); roadOverlay.setPoints(geoPoints); - roadOverlay.setColor(R.color.red); + + // this is for mapquest, but it gives a "no value for guidancelinkcollection" error and google has never heard of that +// GeoPoint[] gp = directionsResult.getStartAndEndPoint(); +// ArrayList arrayList = new ArrayList<>(Arrays.asList(gp)); +// Road road = roadManager.getRoad(arrayList); +// roadOverlay = RoadManager.buildRoadOverlay(road); + + roadOverlay.setColor(color); CurrentRoute.INSTANCE.setCurrentRoute(roadOverlay); @@ -137,19 +150,6 @@ public class HomeFragment extends Fragment { mLocationOverlay.enableMyLocation(); mapView.getOverlays().add(mLocationOverlay); -// CustomOverlay customOverlay = new CustomOverlay(getResources().getDrawable(R.drawable.ic_baseline_location_on_24),mapView); -// -// for (com.a1.nextlocation.data.Location l : LocationListManager.INSTANCE.getLocationList()) { -// GeoPoint p = new GeoPoint(l.getLat(), l.getLong()); -// OverlayItem overlayItem = new OverlayItem(l.getName(),l.getDescription(), p); -// -// customOverlay.addOverlayItem(overlayItem); -// Log.d(TAG, "initMap: " + "succes"); -// } - - -// mapView.getOverlays().add(customOverlay); - // add the zoom controller IMapController mapController = mapView.getController(); mapController.setZoom(15.0); @@ -158,10 +158,15 @@ public class HomeFragment extends Fragment { LocationManager locationManager = (LocationManager) requireActivity().getSystemService(Context.LOCATION_SERVICE); + try { + + locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); - GeoPoint startPoint = new GeoPoint(location.getLatitude(), location.getLongitude()); - mapController.setCenter(startPoint); + if( location != null ) { + currentLocation = new GeoPoint(location.getLatitude(), location.getLongitude()); + mapController.setCenter(currentLocation); + } } catch (SecurityException e) { Log.d(TAG, "onViewCreated: exception while getting location: " + e.getLocalizedMessage()); @@ -205,4 +210,28 @@ public class HomeFragment extends Fragment { REQUEST_PERMISSIONS_REQUEST_CODE); } } + + @Override + public void onLocationChanged(@NonNull Location location) { + + currentLocation = new GeoPoint(location); + IMapController mapController = mapView.getController(); + mapController.animateTo(new GeoPoint(location.getLatitude(),location.getLongitude())); + } + + @Override + public void onProviderEnabled(@NonNull String provider) { + + } + + @Override + public void onProviderDisabled(@NonNull String provider) { + + } + + // this is deprecated but android is stupid and gives an error if I don't override it + @Override + public void onStatusChanged(String provider, int status, Bundle extras) { + + } } \ No newline at end of file diff --git a/app/src/main/java/com/a1/nextlocation/fragments/RouteFragment.java b/app/src/main/java/com/a1/nextlocation/fragments/RouteFragment.java index 85d8c02..0c1b7b1 100644 --- a/app/src/main/java/com/a1/nextlocation/fragments/RouteFragment.java +++ b/app/src/main/java/com/a1/nextlocation/fragments/RouteFragment.java @@ -70,13 +70,14 @@ public class RouteFragment extends Fragment { public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); - ApiHandler.INSTANCE.getDirections(51.49017262451581, 4.289038164073164,51.47337383133509, 4.303535222390562); +// ApiHandler.INSTANCE.getDirections(51.49017262451581, 4.289038164073164,51.47337383133509, 4.303535222390562); Route r = new Route("test"); - r.addLocation(new Location("test",51.487963606716185, 4.280396603442448,"route",null)); - r.addLocation(new Location("test",51.486962126272886, 4.27884897122147,"route",null)); - r.addLocation(new Location("test",51.485412622620224, 4.277392376189963,"route",null)); - r.addLocation(new Location("test",51.4801212376542, 4.281610432511638,"route",null)); - r.addLocation(new Location("test",51.481103969835665, 4.2903500027691805,"route",null)); + r.addLocation(new Location("test",51.574473766034046, 4.7628379328055175,"route",null)); + r.addLocation(new Location("test",51.577354223919876, 4.771120593941968,"route",null)); + r.addLocation(new Location("test",51.573033468635174, 4.782750651807139,"route",null)); + r.addLocation(new Location("test",51.56519104881196, 4.748246716295709,"route",null)); + r.addLocation(new Location("test",51.57367360644676, 4.74404101271347,"route",null)); + r.addLocation(new Location("test",51.57852769146427, 4.739878224473907,"route",null)); // r.addLocation(new Location("test",51.489063681658145, 4.289596063527951,"route",null)); // r.addLocation(new Location("test",51.483012677667766, 4.28003245468457,"route",null)); ApiHandler.INSTANCE.getDirections(r); diff --git a/app/src/main/java/com/a1/nextlocation/network/ApiHandler.java b/app/src/main/java/com/a1/nextlocation/network/ApiHandler.java index 5787b30..570e683 100644 --- a/app/src/main/java/com/a1/nextlocation/network/ApiHandler.java +++ b/app/src/main/java/com/a1/nextlocation/network/ApiHandler.java @@ -131,11 +131,11 @@ public enum ApiHandler { t.start(); -// try { -// t.join(); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } + try { + t.join(); + } catch (InterruptedException e) { + e.printStackTrace(); + } } From 40331f31359b0e5e0371dfc11f72b37909fc3154 Mon Sep 17 00:00:00 2001 From: Sem van der Hoeven Date: Tue, 5 Jan 2021 12:59:35 +0100 Subject: [PATCH 11/21] removed test route --- .../nextlocation/fragments/RouteFragment.java | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/com/a1/nextlocation/fragments/RouteFragment.java b/app/src/main/java/com/a1/nextlocation/fragments/RouteFragment.java index 0c1b7b1..26c5d31 100644 --- a/app/src/main/java/com/a1/nextlocation/fragments/RouteFragment.java +++ b/app/src/main/java/com/a1/nextlocation/fragments/RouteFragment.java @@ -71,15 +71,15 @@ public class RouteFragment extends Fragment { super.onViewCreated(view, savedInstanceState); // ApiHandler.INSTANCE.getDirections(51.49017262451581, 4.289038164073164,51.47337383133509, 4.303535222390562); - Route r = new Route("test"); - r.addLocation(new Location("test",51.574473766034046, 4.7628379328055175,"route",null)); - r.addLocation(new Location("test",51.577354223919876, 4.771120593941968,"route",null)); - r.addLocation(new Location("test",51.573033468635174, 4.782750651807139,"route",null)); - r.addLocation(new Location("test",51.56519104881196, 4.748246716295709,"route",null)); - r.addLocation(new Location("test",51.57367360644676, 4.74404101271347,"route",null)); - r.addLocation(new Location("test",51.57852769146427, 4.739878224473907,"route",null)); -// r.addLocation(new Location("test",51.489063681658145, 4.289596063527951,"route",null)); -// r.addLocation(new Location("test",51.483012677667766, 4.28003245468457,"route",null)); - ApiHandler.INSTANCE.getDirections(r); +// Route r = new Route("test"); +// r.addLocation(new Location("test",51.574473766034046, 4.7628379328055175,"route",null)); +// r.addLocation(new Location("test",51.577354223919876, 4.771120593941968,"route",null)); +// r.addLocation(new Location("test",51.573033468635174, 4.782750651807139,"route",null)); +// r.addLocation(new Location("test",51.56519104881196, 4.748246716295709,"route",null)); +// r.addLocation(new Location("test",51.57367360644676, 4.74404101271347,"route",null)); +// r.addLocation(new Location("test",51.57852769146427, 4.739878224473907,"route",null)); +//// r.addLocation(new Location("test",51.489063681658145, 4.289596063527951,"route",null)); +//// r.addLocation(new Location("test",51.483012677667766, 4.28003245468457,"route",null)); +// ApiHandler.INSTANCE.getDirections(r); } } \ No newline at end of file From 65d2f31e3f1eb8e7dd59e17532dfd666ca5af3ef Mon Sep 17 00:00:00 2001 From: Sem van der Hoeven Date: Tue, 5 Jan 2021 13:03:42 +0100 Subject: [PATCH 12/21] stuff --- .../a1/nextlocation/fragments/HomeFragment.java | 17 ++++++++++++----- .../fragments/RouteDetailFragment.java | 2 ++ 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/com/a1/nextlocation/fragments/HomeFragment.java b/app/src/main/java/com/a1/nextlocation/fragments/HomeFragment.java index 516db24..f757c11 100644 --- a/app/src/main/java/com/a1/nextlocation/fragments/HomeFragment.java +++ b/app/src/main/java/com/a1/nextlocation/fragments/HomeFragment.java @@ -61,7 +61,7 @@ public class HomeFragment extends Fragment implements LocationListener { private MapView mapView; private final int REQUEST_PERMISSIONS_REQUEST_CODE = 1; private final String TAG = HomeFragment.class.getCanonicalName(); - private RoadManager roadManager; +// private RoadManager roadManager; private Polyline roadOverlay; private int color; @@ -75,8 +75,8 @@ public class HomeFragment extends Fragment implements LocationListener { Manifest.permission.ACCESS_FINE_LOCATION, // WRITE_EXTERNAL_STORAGE is required in order to show the map Manifest.permission.WRITE_EXTERNAL_STORAGE); - roadManager = new MapQuestRoadManager(MAPQUEST_API_KEY); - roadManager.addRequestOption("routeType=foot-walking"); +// roadManager = new MapQuestRoadManager(MAPQUEST_API_KEY); +// roadManager.addRequestOption("routeType=foot-walking"); color = requireContext().getColor(R.color.red); } @@ -93,8 +93,6 @@ public class HomeFragment extends Fragment implements LocationListener { ((FragmentActivity) view.getContext()).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_layout, locationFragment).addToBackStack(null).commit(); }); - -// roadManager.addRequestOption("routeType=foot-walking"); ApiHandler.INSTANCE.addListener(this::onDirectionsAvailable); return view; } @@ -126,6 +124,10 @@ public class HomeFragment extends Fragment implements LocationListener { initMap(view); } + /** + * This method initializes the map and all the things it needs + * @param view the view the map is on + */ private void initMap(@NonNull View view) { // set the user agent Configuration.getInstance().setUserAgentValue(userAgent); @@ -193,6 +195,7 @@ public class HomeFragment extends Fragment implements LocationListener { } } + private void requestPermissionsIfNecessary(String... permissions) { ArrayList permissionsToRequest = new ArrayList<>(); if (this.getContext() != null) @@ -211,6 +214,10 @@ public class HomeFragment extends Fragment implements LocationListener { } } + /** + * animate to the new location + * @param location the new location + */ @Override public void onLocationChanged(@NonNull Location location) { diff --git a/app/src/main/java/com/a1/nextlocation/fragments/RouteDetailFragment.java b/app/src/main/java/com/a1/nextlocation/fragments/RouteDetailFragment.java index d79bfa2..17852b7 100644 --- a/app/src/main/java/com/a1/nextlocation/fragments/RouteDetailFragment.java +++ b/app/src/main/java/com/a1/nextlocation/fragments/RouteDetailFragment.java @@ -34,6 +34,8 @@ public class RouteDetailFragment extends Fragment { this.routeDetailText.setText(this.route.getName()); + + return view; } } \ No newline at end of file From 062739ac7b15e97d38d89360c4f782becea68825 Mon Sep 17 00:00:00 2001 From: Sem van der Hoeven Date: Tue, 5 Jan 2021 16:02:48 +0100 Subject: [PATCH 13/21] added navigation to location from map --- .../com/a1/nextlocation/data/Location.java | 19 +++++ .../{CurrentRoute.java => StaticData.java} | 14 +++- .../nextlocation/fragments/HomeFragment.java | 70 +++++++++++++------ .../fragments/LocationDetailFragment.java | 16 +++++ 4 files changed, 95 insertions(+), 24 deletions(-) rename app/src/main/java/com/a1/nextlocation/data/{CurrentRoute.java => StaticData.java} (52%) diff --git a/app/src/main/java/com/a1/nextlocation/data/Location.java b/app/src/main/java/com/a1/nextlocation/data/Location.java index a0822fc..d8ecb58 100644 --- a/app/src/main/java/com/a1/nextlocation/data/Location.java +++ b/app/src/main/java/com/a1/nextlocation/data/Location.java @@ -108,6 +108,25 @@ public class Location implements Parcelable { return long1 + "," + lat1; } + public double getDistance(Location other) { + double dlon = other.getLong() - getLong(); + double dlat = other.getLat() - getLong(); + double a = Math.pow(Math.sin(dlat / 2), 2) + + Math.cos(getLat()) * Math.cos(other.getLong()) + * Math.pow(Math.sin(dlon / 2),2); + + double c = 2 * Math.asin(Math.sqrt(a)); + + // Radius of earth in kilometers. Use 3956 + // for miles + double r = 6371; + + // calculate the result + double distance = c * r; + + return Math.floor(distance); + } + public GeoPoint convertToGeoPoint() { return new GeoPoint(this.getLat(),this.getLong()); } diff --git a/app/src/main/java/com/a1/nextlocation/data/CurrentRoute.java b/app/src/main/java/com/a1/nextlocation/data/StaticData.java similarity index 52% rename from app/src/main/java/com/a1/nextlocation/data/CurrentRoute.java rename to app/src/main/java/com/a1/nextlocation/data/StaticData.java index a0642f0..7114803 100644 --- a/app/src/main/java/com/a1/nextlocation/data/CurrentRoute.java +++ b/app/src/main/java/com/a1/nextlocation/data/StaticData.java @@ -2,8 +2,20 @@ package com.a1.nextlocation.data; import org.osmdroid.views.overlay.Polyline; -public enum CurrentRoute { +/** + * singleton to keep track of different global data + */ +public enum StaticData { INSTANCE; + private double distanceTraveled = 0; + + public void addDistance(double d) { + distanceTraveled += d; + } + + public double getDistanceTraveled() { + return distanceTraveled; + } private Polyline currentRoute; diff --git a/app/src/main/java/com/a1/nextlocation/fragments/HomeFragment.java b/app/src/main/java/com/a1/nextlocation/fragments/HomeFragment.java index 4e0db7b..2aedc11 100644 --- a/app/src/main/java/com/a1/nextlocation/fragments/HomeFragment.java +++ b/app/src/main/java/com/a1/nextlocation/fragments/HomeFragment.java @@ -5,7 +5,6 @@ package com.a1.nextlocation.fragments; import android.Manifest; import android.content.Context; import android.content.pm.PackageManager; -import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.location.Location; import android.location.LocationListener; @@ -26,19 +25,12 @@ import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import com.a1.nextlocation.R; -import com.a1.nextlocation.data.CurrentRoute; -import com.a1.nextlocation.data.Route; +import com.a1.nextlocation.data.StaticData; import com.a1.nextlocation.json.DirectionsResult; import com.a1.nextlocation.network.ApiHandler; -import com.a1.nextlocation.recyclerview.CouponListManager; -import com.a1.nextlocation.recyclerview.CustomOverlay; import com.a1.nextlocation.recyclerview.LocationListManager; import org.osmdroid.api.IMapController; -import org.osmdroid.bonuspack.routing.MapQuestRoadManager; -import org.osmdroid.bonuspack.routing.OSRMRoadManager; -import org.osmdroid.bonuspack.routing.Road; -import org.osmdroid.bonuspack.routing.RoadManager; import org.osmdroid.config.Configuration; import org.osmdroid.util.GeoPoint; import org.osmdroid.views.MapView; @@ -52,11 +44,9 @@ import org.osmdroid.views.overlay.mylocation.GpsMyLocationProvider; import org.osmdroid.views.overlay.mylocation.MyLocationNewOverlay; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; import java.util.List; -public class HomeFragment extends Fragment { +public class HomeFragment extends Fragment implements LocationListener{ private final String userAgent = "com.ai.nextlocation.fragments"; public final static String MAPQUEST_API_KEY = "vuyXjqnAADpjeL9QwtgWGleIk95e36My"; private ImageButton imageButton; @@ -66,8 +56,7 @@ public class HomeFragment extends Fragment { // private RoadManager roadManager; private Polyline roadOverlay; private int color; - - private GeoPoint currentLocation; + private Location currentLocation; @Override public void onCreate(Bundle savedInstanceState) { @@ -114,7 +103,7 @@ public class HomeFragment extends Fragment { roadOverlay.setColor(color); - CurrentRoute.INSTANCE.setCurrentRoute(roadOverlay); + StaticData.INSTANCE.setCurrentRoute(roadOverlay); Log.d(TAG, "onDirectionsAvailable: successfully added road!"); } @@ -148,6 +137,8 @@ public class HomeFragment extends Fragment { compassOverlay.enableCompass(); mapView.getOverlays().add(compassOverlay); + addLocations(); + // add the location overlay MyLocationNewOverlay mLocationOverlay = new MyLocationNewOverlay(gpsMyLocationProvider, mapView); mLocationOverlay.enableFollowLocation(); @@ -165,9 +156,13 @@ public class HomeFragment extends Fragment { try { Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); + if (currentLocation == null) { + currentLocation = location; + } + if( location != null ) { - currentLocation = new GeoPoint(location.getLatitude(), location.getLongitude()); - mapController.setCenter(currentLocation); + GeoPoint start = new GeoPoint(location.getLatitude(), location.getLongitude()); + mapController.setCenter(start); } } catch (SecurityException e) { @@ -183,15 +178,14 @@ public class HomeFragment extends Fragment { displayRoute(); - addLocations(); } private void displayRoute() { if (roadOverlay == null) { - if (CurrentRoute.INSTANCE.getCurrentRoute() != null) { - roadOverlay = CurrentRoute.INSTANCE.getCurrentRoute(); + if (StaticData.INSTANCE.getCurrentRoute() != null) { + roadOverlay = StaticData.INSTANCE.getCurrentRoute(); mapView.getOverlays().add(roadOverlay); mapView.invalidate(); Log.d(TAG, "initMap: successfully added road!"); @@ -206,7 +200,9 @@ public class HomeFragment extends Fragment { private void addLocations() { List locations = LocationListManager.INSTANCE.getLocationList(); final ArrayList items = new ArrayList<>(locations.size()); - Drawable marker = this.getResources().getDrawable(R.drawable.ic_baseline_location_on_24); + Drawable marker = ContextCompat.getDrawable(requireContext(),R.drawable.ic_baseline_location_on_24); + marker.setAlpha(255); + marker.setTint(getResources().getColor(R.color.primaryColour)); for (com.a1.nextlocation.data.Location location : locations) { OverlayItem item = new OverlayItem(location.getName(),location.getDescription(),location.convertToGeoPoint()); item.setMarker(marker); @@ -216,13 +212,19 @@ public class HomeFragment extends Fragment { new ItemizedIconOverlay.OnItemGestureListener() { @Override public boolean onItemSingleTapUp(int index, OverlayItem item) { - + com.a1.nextlocation.data.Location clicked = locations.get(index); + requireActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragment_layout, new LocationDetailFragment(clicked)).commit(); return false; } @Override public boolean onItemLongPress(int index, OverlayItem item) { - Toast.makeText(requireContext(), locations.get(index).getName(),Toast.LENGTH_SHORT).show(); + com.a1.nextlocation.data.Location clicked = locations.get(index); + Toast.makeText(requireContext(), clicked.getName(),Toast.LENGTH_SHORT).show(); +// Route route = new Route("Route to " + clicked.getName()); +// route.addLocation(new com.a1.nextlocation.data.Location("Current location",currentLocation.getLatitude(),currentLocation.getLongitude(),"your location",null)); +// route.addLocation(clicked); +// ApiHandler.INSTANCE.getDirections(route); return true; } },requireContext()); @@ -249,4 +251,26 @@ public class HomeFragment extends Fragment { REQUEST_PERMISSIONS_REQUEST_CODE); } } + + @Override + public void onLocationChanged(@NonNull Location location) { + double distance = currentLocation.distanceTo(location); // in meters + StaticData.INSTANCE.addDistance(distance); + currentLocation = location; + } + + @Override + public void onStatusChanged(String provider, int status, Bundle extras) { + + } + + @Override + public void onProviderEnabled(@NonNull String provider) { + + } + + @Override + public void onProviderDisabled(@NonNull String provider) { + + } } \ No newline at end of file diff --git a/app/src/main/java/com/a1/nextlocation/fragments/LocationDetailFragment.java b/app/src/main/java/com/a1/nextlocation/fragments/LocationDetailFragment.java index 82bcabb..19f73cd 100644 --- a/app/src/main/java/com/a1/nextlocation/fragments/LocationDetailFragment.java +++ b/app/src/main/java/com/a1/nextlocation/fragments/LocationDetailFragment.java @@ -1,20 +1,33 @@ package com.a1.nextlocation.fragments; +import android.content.Intent; import android.os.Bundle; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; +import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import com.a1.nextlocation.R; +import com.a1.nextlocation.data.Location; public class LocationDetailFragment extends Fragment { + private static final String TAG = LocationDetailFragment.class.getCanonicalName(); private ImageButton imageButton; + private Location location; + + public LocationDetailFragment() { + + } + + public LocationDetailFragment(Location location) { + this.location = location; + } @Override public void onCreate(Bundle savedInstanceState) { @@ -31,6 +44,9 @@ public class LocationDetailFragment extends Fragment { ((FragmentActivity) view.getContext()).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_layout, locationFragment).addToBackStack(null).commit(); }); + if (location != null) { + Log.d(TAG, "onCreateView: the location has a name of: " + location.getName()); + } return view; } } \ No newline at end of file From 587380fd893d8ffe543aee6f5a08d9386aba6bb4 Mon Sep 17 00:00:00 2001 From: Sem van der Hoeven Date: Tue, 5 Jan 2021 16:39:12 +0100 Subject: [PATCH 14/21] added updating location when you're close to it --- app/src/main/assets/locations.json | 2 +- .../com/a1/nextlocation/data/Location.java | 23 +++++++++++++++++++ .../com/a1/nextlocation/data/StaticData.java | 17 ++++++++++++++ .../nextlocation/fragments/HomeFragment.java | 15 ++++++++++++ .../fragments/StatisticFragment.java | 8 +++++++ .../main/res/layout/fragment_statistic.xml | 2 ++ 6 files changed, 66 insertions(+), 1 deletion(-) diff --git a/app/src/main/assets/locations.json b/app/src/main/assets/locations.json index 1bbddb1..c754cd3 100644 --- a/app/src/main/assets/locations.json +++ b/app/src/main/assets/locations.json @@ -82,7 +82,7 @@ "name":"MEZZ Breda Keizerstraat 101", "coordinates":"51.58394697737321,4.779757901349616", "description":"4811HL Breda", - "imageUrl":"NULL" + "imageUrl":"mezz_breda" }, { "name":"Het Klooster Breda Schorsmolenstraat 13", diff --git a/app/src/main/java/com/a1/nextlocation/data/Location.java b/app/src/main/java/com/a1/nextlocation/data/Location.java index d8ecb58..ed4ccc8 100644 --- a/app/src/main/java/com/a1/nextlocation/data/Location.java +++ b/app/src/main/java/com/a1/nextlocation/data/Location.java @@ -35,6 +35,10 @@ public class Location implements Parcelable { this(name,getStringFromCoordinates(latCoord,longCoord),description,imageUrl); } + public Location(String name, android.location.Location loc, String description, String imageUrl) { + this(name,getStringFromCoordinates(loc.getLatitude(),loc.getLongitude()),description,imageUrl); + } + protected Location(Parcel in) { name = in.readString(); coordinates = in.readString(); @@ -127,6 +131,25 @@ public class Location implements Parcelable { return Math.floor(distance); } + public static double getDistance(double lat1, double lon1, double lat2, double lon2) { + double dlon = lon2 - lon1; + double dlat = lat2 - lat1; + double a = Math.pow(Math.sin(dlat / 2), 2) + + Math.cos(lat1) * Math.cos(lat2) + * Math.pow(Math.sin(dlon / 2),2); + + double c = 2 * Math.asin(Math.sqrt(a)); + + // Radius of earth in kilometers. Use 3956 + // for miles + double r = 6371; + + // calculate the result + double distance = c * r; + + return Math.floor(distance); + } + public GeoPoint convertToGeoPoint() { return new GeoPoint(this.getLat(),this.getLong()); } diff --git a/app/src/main/java/com/a1/nextlocation/data/StaticData.java b/app/src/main/java/com/a1/nextlocation/data/StaticData.java index 7114803..0f0d4e3 100644 --- a/app/src/main/java/com/a1/nextlocation/data/StaticData.java +++ b/app/src/main/java/com/a1/nextlocation/data/StaticData.java @@ -2,21 +2,38 @@ package com.a1.nextlocation.data; import org.osmdroid.views.overlay.Polyline; +import java.util.ArrayList; + /** * singleton to keep track of different global data */ public enum StaticData { INSTANCE; private double distanceTraveled = 0; + private int locationsVisited = 0; + + private ArrayList visitedNames = new ArrayList<>(); public void addDistance(double d) { distanceTraveled += d; } + public double getDistanceTraveled() { return distanceTraveled; } + public void visitLocation(Location location) { + if (!visitedNames.contains(location.getName())) { + locationsVisited++; + visitedNames.add(location.getName()); + } + } + + public int getLocationsVisited() { + return locationsVisited; + } + private Polyline currentRoute; public void setCurrentRoute(Polyline currentRoute) { diff --git a/app/src/main/java/com/a1/nextlocation/fragments/HomeFragment.java b/app/src/main/java/com/a1/nextlocation/fragments/HomeFragment.java index 2aedc11..c20724b 100644 --- a/app/src/main/java/com/a1/nextlocation/fragments/HomeFragment.java +++ b/app/src/main/java/com/a1/nextlocation/fragments/HomeFragment.java @@ -154,7 +154,12 @@ public class HomeFragment extends Fragment implements LocationListener{ + try { + + locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,this); + locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,this); + Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (currentLocation == null) { currentLocation = location; @@ -257,6 +262,16 @@ public class HomeFragment extends Fragment implements LocationListener{ double distance = currentLocation.distanceTo(location); // in meters StaticData.INSTANCE.addDistance(distance); currentLocation = location; + + Thread t = new Thread(() -> { + for (com.a1.nextlocation.data.Location l : LocationListManager.INSTANCE.getLocationList()) { + if (com.a1.nextlocation.data.Location.getDistance(currentLocation.getLatitude(),currentLocation.getLongitude(),l.getLat(),l.getLong()) < 10) { + StaticData.INSTANCE.visitLocation(l); + } + } + }); + + t.start(); } @Override diff --git a/app/src/main/java/com/a1/nextlocation/fragments/StatisticFragment.java b/app/src/main/java/com/a1/nextlocation/fragments/StatisticFragment.java index a4080c5..83e3a07 100644 --- a/app/src/main/java/com/a1/nextlocation/fragments/StatisticFragment.java +++ b/app/src/main/java/com/a1/nextlocation/fragments/StatisticFragment.java @@ -16,6 +16,7 @@ import android.widget.Toast; import com.a1.nextlocation.R; import com.a1.nextlocation.data.Coupon; +import com.a1.nextlocation.data.StaticData; import com.a1.nextlocation.recyclerview.CouponAdapter; import com.a1.nextlocation.recyclerview.CouponListManager; @@ -36,6 +37,13 @@ public class StatisticFragment extends Fragment { public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_statistic, container, false); + TextView distance = view.findViewById(R.id.statistics_km); + TextView locs = view.findViewById(R.id.statistics_locations_visited); + double dist = StaticData.INSTANCE.getDistanceTraveled()/1000; + distance.setText("" + String.format("%.1f",dist) + " km"); + locs.setText("" + StaticData.INSTANCE.getLocationsVisited()); + + this.couponList = CouponListManager.INSTANCE.getCouponList(); CouponAdapter adapter = new CouponAdapter(this.getContext(), this.couponList); TextView couponNumber = view.findViewById(R.id.couponAmount); diff --git a/app/src/main/res/layout/fragment_statistic.xml b/app/src/main/res/layout/fragment_statistic.xml index 5abfdc0..ad0864e 100644 --- a/app/src/main/res/layout/fragment_statistic.xml +++ b/app/src/main/res/layout/fragment_statistic.xml @@ -55,6 +55,7 @@ /> Date: Wed, 6 Jan 2021 10:36:37 +0100 Subject: [PATCH 15/21] comment --- .../main/java/com/a1/nextlocation/fragments/HomeFragment.java | 1 + 1 file changed, 1 insertion(+) diff --git a/app/src/main/java/com/a1/nextlocation/fragments/HomeFragment.java b/app/src/main/java/com/a1/nextlocation/fragments/HomeFragment.java index c20724b..1786782 100644 --- a/app/src/main/java/com/a1/nextlocation/fragments/HomeFragment.java +++ b/app/src/main/java/com/a1/nextlocation/fragments/HomeFragment.java @@ -263,6 +263,7 @@ public class HomeFragment extends Fragment implements LocationListener{ StaticData.INSTANCE.addDistance(distance); currentLocation = location; + //new thread because we don't want the main thread to hang Thread t = new Thread(() -> { for (com.a1.nextlocation.data.Location l : LocationListManager.INSTANCE.getLocationList()) { if (com.a1.nextlocation.data.Location.getDistance(currentLocation.getLatitude(),currentLocation.getLongitude(),l.getLat(),l.getLong()) < 10) { From 1877a693d00dde90bff6332841a25e76603ddab7 Mon Sep 17 00:00:00 2001 From: Sem van der Hoeven Date: Wed, 6 Jan 2021 10:40:20 +0100 Subject: [PATCH 16/21] added boolean to singleton --- .../java/com/a1/nextlocation/data/StaticData.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/app/src/main/java/com/a1/nextlocation/data/StaticData.java b/app/src/main/java/com/a1/nextlocation/data/StaticData.java index 0f0d4e3..fe861d1 100644 --- a/app/src/main/java/com/a1/nextlocation/data/StaticData.java +++ b/app/src/main/java/com/a1/nextlocation/data/StaticData.java @@ -11,6 +11,20 @@ public enum StaticData { INSTANCE; private double distanceTraveled = 0; private int locationsVisited = 0; + private boolean isFollowingRoute = false; + private String routeName = ""; + + public void followRoute(Route route) { + routeName = route.getName(); + setFollowingRoute(true); + } + public void setFollowingRoute(boolean followingRoute) { + isFollowingRoute = followingRoute; + } + + public boolean isFollowingRoute() { + return isFollowingRoute; + } private ArrayList visitedNames = new ArrayList<>(); From abc58d360650dfb42fcbdc9e88d3a153dcdf6fbb Mon Sep 17 00:00:00 2001 From: Sem van der Hoeven Date: Wed, 6 Jan 2021 10:41:56 +0100 Subject: [PATCH 17/21] following route stuff --- app/src/main/java/com/a1/nextlocation/data/StaticData.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/app/src/main/java/com/a1/nextlocation/data/StaticData.java b/app/src/main/java/com/a1/nextlocation/data/StaticData.java index fe861d1..0043e3d 100644 --- a/app/src/main/java/com/a1/nextlocation/data/StaticData.java +++ b/app/src/main/java/com/a1/nextlocation/data/StaticData.java @@ -18,6 +18,10 @@ public enum StaticData { routeName = route.getName(); setFollowingRoute(true); } + + public boolean isFollowingRoute(Route route) { + return isFollowingRoute && route.getName().equals(routeName); + } public void setFollowingRoute(boolean followingRoute) { isFollowingRoute = followingRoute; } From f6af7ae80b2ad5e69f90f6df3801b4a60939092b Mon Sep 17 00:00:00 2001 From: Sem van der Hoeven Date: Wed, 6 Jan 2021 10:48:03 +0100 Subject: [PATCH 18/21] added route singleton --- .../a1/nextlocation/data/RouteHandler.java | 42 +++++++++++++++++++ .../com/a1/nextlocation/data/StaticData.java | 18 -------- .../fragments/RouteDetailFragment.java | 3 ++ .../a1/nextlocation/network/ApiHandler.java | 1 + 4 files changed, 46 insertions(+), 18 deletions(-) create mode 100644 app/src/main/java/com/a1/nextlocation/data/RouteHandler.java diff --git a/app/src/main/java/com/a1/nextlocation/data/RouteHandler.java b/app/src/main/java/com/a1/nextlocation/data/RouteHandler.java new file mode 100644 index 0000000..65fda9b --- /dev/null +++ b/app/src/main/java/com/a1/nextlocation/data/RouteHandler.java @@ -0,0 +1,42 @@ +package com.a1.nextlocation.data; + +/** + * singleton to track the current route that is being followed + */ +public enum RouteHandler { + INSTANCE; + + private boolean isFollowingRoute = false; + private Route currentRoute; + private int stepCount = 0; + + public int getStepCount() { + return stepCount; + } + + public void addStep() { + stepCount++; + } + + public void finishRoute() { + stepCount = 0; + isFollowingRoute = false; + currentRoute = null; + } + + public void followRoute(Route route) { + this.currentRoute = route; + setFollowingRoute(true); + } + + public boolean isFollowingRoute(Route route) { + return isFollowingRoute && route.equals(currentRoute); + } + public void setFollowingRoute(boolean followingRoute) { + isFollowingRoute = followingRoute; + } + + public boolean isFollowingRoute() { + return isFollowingRoute; + } +} diff --git a/app/src/main/java/com/a1/nextlocation/data/StaticData.java b/app/src/main/java/com/a1/nextlocation/data/StaticData.java index 0043e3d..0f0d4e3 100644 --- a/app/src/main/java/com/a1/nextlocation/data/StaticData.java +++ b/app/src/main/java/com/a1/nextlocation/data/StaticData.java @@ -11,24 +11,6 @@ public enum StaticData { INSTANCE; private double distanceTraveled = 0; private int locationsVisited = 0; - private boolean isFollowingRoute = false; - private String routeName = ""; - - public void followRoute(Route route) { - routeName = route.getName(); - setFollowingRoute(true); - } - - public boolean isFollowingRoute(Route route) { - return isFollowingRoute && route.getName().equals(routeName); - } - public void setFollowingRoute(boolean followingRoute) { - isFollowingRoute = followingRoute; - } - - public boolean isFollowingRoute() { - return isFollowingRoute; - } private ArrayList visitedNames = new ArrayList<>(); diff --git a/app/src/main/java/com/a1/nextlocation/fragments/RouteDetailFragment.java b/app/src/main/java/com/a1/nextlocation/fragments/RouteDetailFragment.java index 99e3445..5fded7c 100644 --- a/app/src/main/java/com/a1/nextlocation/fragments/RouteDetailFragment.java +++ b/app/src/main/java/com/a1/nextlocation/fragments/RouteDetailFragment.java @@ -14,6 +14,8 @@ import android.widget.Toast; import com.a1.nextlocation.R; import com.a1.nextlocation.data.Route; +import com.a1.nextlocation.data.RouteHandler; +import com.a1.nextlocation.data.StaticData; import com.a1.nextlocation.network.ApiHandler; public class RouteDetailFragment extends Fragment { @@ -45,6 +47,7 @@ public class RouteDetailFragment extends Fragment { public void startRoute(View view) { ApiHandler.INSTANCE.getDirections(route); + RouteHandler.INSTANCE.followRoute(route); Toast.makeText(requireContext(),"Route started!",Toast.LENGTH_SHORT).show(); ((FragmentActivity) view.getContext()).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_layout, new HomeFragment()).addToBackStack(null).commit(); diff --git a/app/src/main/java/com/a1/nextlocation/network/ApiHandler.java b/app/src/main/java/com/a1/nextlocation/network/ApiHandler.java index 570e683..46d3830 100644 --- a/app/src/main/java/com/a1/nextlocation/network/ApiHandler.java +++ b/app/src/main/java/com/a1/nextlocation/network/ApiHandler.java @@ -127,6 +127,7 @@ public enum ApiHandler { } catch (IOException e) { Log.d(TAG, "getDirections: caught exception: " + e.getLocalizedMessage()); } + }); t.start(); From f5da1c8a83b056d067311e94fdd876a118fab3fa Mon Sep 17 00:00:00 2001 From: Sem van der Hoeven Date: Wed, 6 Jan 2021 11:33:15 +0100 Subject: [PATCH 19/21] added displaying all locations upon stopping the route --- .../a1/nextlocation/data/RouteHandler.java | 27 +++++++ .../com/a1/nextlocation/data/StaticData.java | 8 --- .../nextlocation/fragments/HomeFragment.java | 68 +++++++++++------- .../main/res/drawable-anydpi/ic_stop_icon.xml | 12 ++++ .../main/res/drawable-hdpi/ic_stop_icon.png | Bin 0 -> 318 bytes .../main/res/drawable-mdpi/ic_stop_icon.png | Bin 0 -> 213 bytes .../main/res/drawable-xhdpi/ic_stop_icon.png | Bin 0 -> 416 bytes .../main/res/drawable-xxhdpi/ic_stop_icon.png | Bin 0 -> 552 bytes app/src/main/res/layout/fragment_home.xml | 11 +++ app/src/main/res/values/strings.xml | 1 + 10 files changed, 95 insertions(+), 32 deletions(-) create mode 100644 app/src/main/res/drawable-anydpi/ic_stop_icon.xml create mode 100644 app/src/main/res/drawable-hdpi/ic_stop_icon.png create mode 100644 app/src/main/res/drawable-mdpi/ic_stop_icon.png create mode 100644 app/src/main/res/drawable-xhdpi/ic_stop_icon.png create mode 100644 app/src/main/res/drawable-xxhdpi/ic_stop_icon.png diff --git a/app/src/main/java/com/a1/nextlocation/data/RouteHandler.java b/app/src/main/java/com/a1/nextlocation/data/RouteHandler.java index 65fda9b..0075475 100644 --- a/app/src/main/java/com/a1/nextlocation/data/RouteHandler.java +++ b/app/src/main/java/com/a1/nextlocation/data/RouteHandler.java @@ -1,5 +1,7 @@ package com.a1.nextlocation.data; +import org.osmdroid.views.overlay.Polyline; + /** * singleton to track the current route that is being followed */ @@ -9,6 +11,21 @@ public enum RouteHandler { private boolean isFollowingRoute = false; private Route currentRoute; private int stepCount = 0; + private RouteFinishedListener routeFinishedListener; + + private Polyline currentRouteLine; + + public void setCurrentRouteLine(Polyline currentRouteLine) { + this.currentRouteLine = currentRouteLine; + } + + public Polyline getCurrentRouteLine() { + return currentRouteLine; + } + + public void setRouteFinishedListener(RouteFinishedListener routeFinishedListener) { + this.routeFinishedListener = routeFinishedListener; + } public int getStepCount() { return stepCount; @@ -22,6 +39,7 @@ public enum RouteHandler { stepCount = 0; isFollowingRoute = false; currentRoute = null; + currentRouteLine = null; } public void followRoute(Route route) { @@ -39,4 +57,13 @@ public enum RouteHandler { public boolean isFollowingRoute() { return isFollowingRoute; } + + public Route getCurrentRoute() { + return currentRoute; + } + + @FunctionalInterface + public interface RouteFinishedListener { + void onRouteFinish(); + } } diff --git a/app/src/main/java/com/a1/nextlocation/data/StaticData.java b/app/src/main/java/com/a1/nextlocation/data/StaticData.java index 0f0d4e3..d347d42 100644 --- a/app/src/main/java/com/a1/nextlocation/data/StaticData.java +++ b/app/src/main/java/com/a1/nextlocation/data/StaticData.java @@ -34,14 +34,6 @@ public enum StaticData { return locationsVisited; } - private Polyline currentRoute; - public void setCurrentRoute(Polyline currentRoute) { - this.currentRoute = currentRoute; - } - - public Polyline getCurrentRoute() { - return currentRoute; - } } diff --git a/app/src/main/java/com/a1/nextlocation/fragments/HomeFragment.java b/app/src/main/java/com/a1/nextlocation/fragments/HomeFragment.java index 1786782..4a8ca4a 100644 --- a/app/src/main/java/com/a1/nextlocation/fragments/HomeFragment.java +++ b/app/src/main/java/com/a1/nextlocation/fragments/HomeFragment.java @@ -1,7 +1,6 @@ package com.a1.nextlocation.fragments; - import android.Manifest; import android.content.Context; import android.content.pm.PackageManager; @@ -25,6 +24,7 @@ import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import com.a1.nextlocation.R; +import com.a1.nextlocation.data.RouteHandler; import com.a1.nextlocation.data.StaticData; import com.a1.nextlocation.json.DirectionsResult; import com.a1.nextlocation.network.ApiHandler; @@ -46,17 +46,19 @@ import org.osmdroid.views.overlay.mylocation.MyLocationNewOverlay; import java.util.ArrayList; import java.util.List; -public class HomeFragment extends Fragment implements LocationListener{ +public class HomeFragment extends Fragment implements LocationListener { private final String userAgent = "com.ai.nextlocation.fragments"; public final static String MAPQUEST_API_KEY = "vuyXjqnAADpjeL9QwtgWGleIk95e36My"; private ImageButton imageButton; + private ImageButton stopButton; private MapView mapView; private final int REQUEST_PERMISSIONS_REQUEST_CODE = 1; private final String TAG = HomeFragment.class.getCanonicalName(); -// private RoadManager roadManager; + // private RoadManager roadManager; private Polyline roadOverlay; private int color; private Location currentLocation; + private Overlay allLocationsOverlay; @Override public void onCreate(Bundle savedInstanceState) { @@ -84,6 +86,23 @@ public class HomeFragment extends Fragment implements LocationListener{ ((FragmentActivity) view.getContext()).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_layout, locationFragment).addToBackStack(null).commit(); }); + stopButton = view.findViewById(R.id.home_stop_route_button); + stopButton.setOnClickListener(v -> { + RouteHandler.INSTANCE.finishRoute(); + stopButton.setVisibility(View.GONE); + Toast.makeText(requireContext(),getResources().getString(R.string.route_stop_toast),Toast.LENGTH_SHORT).show(); + mapView.getOverlays().remove(roadOverlay); + mapView.getOverlays().remove(allLocationsOverlay); + addLocations(); + mapView.invalidate(); + roadOverlay = null; + }); + + if (RouteHandler.INSTANCE.isFollowingRoute()) { + stopButton.setVisibility(View.VISIBLE); + } else { + stopButton.setVisibility(View.GONE); + } ApiHandler.INSTANCE.addListener(this::onDirectionsAvailable); return view; } @@ -103,7 +122,7 @@ public class HomeFragment extends Fragment implements LocationListener{ roadOverlay.setColor(color); - StaticData.INSTANCE.setCurrentRoute(roadOverlay); + RouteHandler.INSTANCE.setCurrentRouteLine(roadOverlay); Log.d(TAG, "onDirectionsAvailable: successfully added road!"); } @@ -117,6 +136,7 @@ public class HomeFragment extends Fragment implements LocationListener{ /** * This method initializes the map and all the things it needs + * * @param view the view the map is on */ private void initMap(@NonNull View view) { @@ -133,7 +153,7 @@ public class HomeFragment extends Fragment implements LocationListener{ GpsMyLocationProvider gpsMyLocationProvider = new GpsMyLocationProvider(this.requireContext()); // add the compass overlay - CompassOverlay compassOverlay = new CompassOverlay(requireContext(),new InternalCompassOrientationProvider(requireContext()),mapView); + CompassOverlay compassOverlay = new CompassOverlay(requireContext(), new InternalCompassOrientationProvider(requireContext()), mapView); compassOverlay.enableCompass(); mapView.getOverlays().add(compassOverlay); @@ -153,19 +173,17 @@ public class HomeFragment extends Fragment implements LocationListener{ LocationManager locationManager = (LocationManager) requireActivity().getSystemService(Context.LOCATION_SERVICE); - - try { - locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,this); - locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,this); + locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); + locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this); Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (currentLocation == null) { currentLocation = location; } - if( location != null ) { + if (location != null) { GeoPoint start = new GeoPoint(location.getLatitude(), location.getLongitude()); mapController.setCenter(start); } @@ -188,32 +206,34 @@ public class HomeFragment extends Fragment implements LocationListener{ private void displayRoute() { - if (roadOverlay == null) { - if (StaticData.INSTANCE.getCurrentRoute() != null) { - roadOverlay = StaticData.INSTANCE.getCurrentRoute(); + if (RouteHandler.INSTANCE.isFollowingRoute()) { + if (roadOverlay == null) { + if (RouteHandler.INSTANCE.getCurrentRouteLine() != null) { + roadOverlay = RouteHandler.INSTANCE.getCurrentRouteLine(); + mapView.getOverlays().add(roadOverlay); + mapView.invalidate(); + Log.d(TAG, "initMap: successfully added road!"); + } + } else { mapView.getOverlays().add(roadOverlay); mapView.invalidate(); Log.d(TAG, "initMap: successfully added road!"); } - } else { - mapView.getOverlays().add(roadOverlay); - mapView.invalidate(); - Log.d(TAG, "initMap: successfully added road!"); } } private void addLocations() { - List locations = LocationListManager.INSTANCE.getLocationList(); + List locations = RouteHandler.INSTANCE.isFollowingRoute() ? RouteHandler.INSTANCE.getCurrentRoute().getLocations() : LocationListManager.INSTANCE.getLocationList(); final ArrayList items = new ArrayList<>(locations.size()); - Drawable marker = ContextCompat.getDrawable(requireContext(),R.drawable.ic_baseline_location_on_24); + Drawable marker = ContextCompat.getDrawable(requireContext(), R.drawable.ic_baseline_location_on_24); marker.setAlpha(255); marker.setTint(getResources().getColor(R.color.primaryColour)); for (com.a1.nextlocation.data.Location location : locations) { - OverlayItem item = new OverlayItem(location.getName(),location.getDescription(),location.convertToGeoPoint()); + OverlayItem item = new OverlayItem(location.getName(), location.getDescription(), location.convertToGeoPoint()); item.setMarker(marker); items.add(item); } - Overlay allLocationsOverlay = new ItemizedIconOverlay(items, + allLocationsOverlay = new ItemizedIconOverlay(items, new ItemizedIconOverlay.OnItemGestureListener() { @Override public boolean onItemSingleTapUp(int index, OverlayItem item) { @@ -225,14 +245,14 @@ public class HomeFragment extends Fragment implements LocationListener{ @Override public boolean onItemLongPress(int index, OverlayItem item) { com.a1.nextlocation.data.Location clicked = locations.get(index); - Toast.makeText(requireContext(), clicked.getName(),Toast.LENGTH_SHORT).show(); + Toast.makeText(requireContext(), clicked.getName(), Toast.LENGTH_SHORT).show(); // Route route = new Route("Route to " + clicked.getName()); // route.addLocation(new com.a1.nextlocation.data.Location("Current location",currentLocation.getLatitude(),currentLocation.getLongitude(),"your location",null)); // route.addLocation(clicked); // ApiHandler.INSTANCE.getDirections(route); return true; } - },requireContext()); + }, requireContext()); mapView.getOverlays().add(allLocationsOverlay); Log.d(TAG, "addLocations: successfully added locations"); @@ -266,7 +286,7 @@ public class HomeFragment extends Fragment implements LocationListener{ //new thread because we don't want the main thread to hang Thread t = new Thread(() -> { for (com.a1.nextlocation.data.Location l : LocationListManager.INSTANCE.getLocationList()) { - if (com.a1.nextlocation.data.Location.getDistance(currentLocation.getLatitude(),currentLocation.getLongitude(),l.getLat(),l.getLong()) < 10) { + if (com.a1.nextlocation.data.Location.getDistance(currentLocation.getLatitude(), currentLocation.getLongitude(), l.getLat(), l.getLong()) < 10) { StaticData.INSTANCE.visitLocation(l); } } diff --git a/app/src/main/res/drawable-anydpi/ic_stop_icon.xml b/app/src/main/res/drawable-anydpi/ic_stop_icon.xml new file mode 100644 index 0000000..addfeb0 --- /dev/null +++ b/app/src/main/res/drawable-anydpi/ic_stop_icon.xml @@ -0,0 +1,12 @@ + + + diff --git a/app/src/main/res/drawable-hdpi/ic_stop_icon.png b/app/src/main/res/drawable-hdpi/ic_stop_icon.png new file mode 100644 index 0000000000000000000000000000000000000000..10f865ca7c0f856343e17b4e500a2ee08c580238 GIT binary patch literal 318 zcmV-E0m1%>P)|3_zKCht6G*@;OCWo3(dfC2Lo@a@*PxNHnVQBPK>Ak|jil{jiM_+%)I-hoO|Z zf;@x}J;)%XoKWx@@8KLiLkaT5LY&P z3t*n5U=~50)jjhAs!PrpDwq{i8~rtHN#K-3uO6zb&;j||rzABOLv<>&_!fGr!a$R^ zqQj)A0AzgO>h}ghn?4|00cglxOabK8$quMe$n0^Fn%!rQMT%8n+u8KIY}NDs2>_ QbpQYW07*qoM6N<$f{KuX}1CrErdaOKJst`6az z-rj59y121D{RIh;%qAwZz?TlD{x|4oV;M3!7RzX6i|3}x=j${i~4xj@%;ZB|w|1FT(P<+ja}GDI!33Bq(Fi-jW`UL!M;2rgDeg^Q1T)edfy)~c< zI(@myRW3TY0Kr-OqdXgw3V-kMn{{Q^(rb&*jDNJSBypp(48 zLD*sv-dap6O+Im;$tO-}@@-|YNOu(h$F<7{o~b!J+N?>EL?CbT($@~1Q?U>L0000< KMNUMnLSTX)D!CH? literal 0 HcmV?d00001 diff --git a/app/src/main/res/drawable-xxhdpi/ic_stop_icon.png b/app/src/main/res/drawable-xxhdpi/ic_stop_icon.png new file mode 100644 index 0000000000000000000000000000000000000000..b8448198dbc8314af7c75381bc4202b4ee7a3afc GIT binary patch literal 552 zcmV+@0@wYCP)SAq6L}2em~ToU;Nj zV{bZZ38|YlI6-c@iG`eYIHHiOz!8IF2~G%UtAu>91}8||mo0|!!Lmgw0Vsx*)H&=r zDM~()tdL_=+^f&6Qh^g#v8MNQsR5!s!F#swA{Vb$P9rv0TH)lP>l!21kSZV_YB|Sy zj;RBpK8hx110K|g{kR1{i`%%?=w$)WqS4I7=4mg0sIN-^wL1dTiX><&fEFd{ciX`U z1G-BkKPyRk03ZMYAYJW5lEyI48|G0cVyeNLYGAU8nzLsDq4kV*pc6;%ra{6X&I#ex?|Rgln2&lxaC)iJ_C4Sj zhUD+V%HJQ;n7B7f$a6{n4RsQ=LEVMAFytgFZq-*Z$8$Ga>YWHGrbqc_+XM3<^zg?5 qGd=4x^{*-X9$k?^5ClOGG(#`TUdl_oYHFGQ0000 + + \ No newline at end of file diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index c322028..cac68cf 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -17,4 +17,5 @@ Coupons gespaard: Coupons Start Route + Route stopped! \ No newline at end of file From 926a984c716910b26ec7fbb595388d6f17159fd6 Mon Sep 17 00:00:00 2001 From: Sem van der Hoeven Date: Wed, 6 Jan 2021 11:33:35 +0100 Subject: [PATCH 20/21] stop icon --- app/src/main/res/drawable/stop_icon.png | Bin 0 -> 4171 bytes 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 app/src/main/res/drawable/stop_icon.png diff --git a/app/src/main/res/drawable/stop_icon.png b/app/src/main/res/drawable/stop_icon.png new file mode 100644 index 0000000000000000000000000000000000000000..7d72917bcdbf5ee205ee3df3f7596c826e5d120a GIT binary patch literal 4171 zcmY*dc{tSD8~@H2F_MDdR)2KwHkwmun&Ard>kKgZk&hwo2ectmv=e*lFpZCxY5f7lm6vY4lK;hk8 zNdN#7kT5`WhhPdxY&Zb`QZjf~XCG?i*QuD?(Ec;fl4H)Xo{GUy=jKi~xrC56$*9hd z(!>G}6dq*i*8joGtH4EZU3GoEecZh3Z!U=Ja=Y(J9~Q4=db+&*8=S!E?-HfSKxLFZ z1#}3M|Cv3IkQVc-l+rq!*RT5BSwT9`oKk&)s^k+?(|Ac{vQv(E6V- zd_?C18Dx|T<-(SAA`oS^OLM{CJ33$0=FiS7Fb!%#r!SUgPeD65Sr9S2ceIbD7zzJ$ z`4_Ys(%{I`v>|vnW@!Ag8Br@k9?P{3f9)Cz>>Lj1iw=jMyn(5$YXM&Dxa_r=K2_Cw zDk%b#n#F|3e z1?T7z3`dM(`~I8mmTD?J_>bT0(@aTuIGUGG#giG69VUwi!-}QD3>jP0n%xU-xAs*H zY+$74>NUJ?mDo9Hos|j2mqKd&t~Kld&?x-TH$ty_uIRbk1_BO@q0?_nhDFy=?ZiXQ zPu|cU3>OW^Dfqswy`2?s!eH>zevZla^r*a!B^!!;f~}6qoDZj(ZbVo#YVr=-6lLw0 z6EW)#;yilKPgET2KO0dkjB3?}rrz^S70+~-3{Atx(T z`bysHtT8W=mEF*iCiQJ4Z~mA{+xX4($HqL_@990cWcD6*v*&`42VM4PPoEENm3y{Q z{Y%Fl%I+3#gHiM{ZlMqp;jb#cqM#RH+p3uSP?s0>p8rZ=OIC!|G=ErUj_jl%PK%co ziE-DflIYE{Dw!v0=ry?c!TATa!^G7lRB3?DJpd*8 zRCpEfT`Y3vxgw`{#;=PLEo(&7U}Wh2&!MpAxIVfbu6% z^KKPrC=>b$eR=-1@Zwn+sz|F&ipz;tqlnf^0SV@oDK1RLqWUz(ig6F~I%@Wr(=qmR zn(F%+!wqZhb9($o^5atzmw^lP=kr{#mETL)pV_M)$d8qxg5fM_YUCo$9eEr35n&-% zNAHL_y;T4*CQOl3Oxt)y>Yb*rI6*D^6zKZIv4jJhPHlI;CujTA zRbz0lu$NPXjfpy7AQT4~9VcfE|M43eX8t+J@;GVH8jPVOnRYuzzp6%ii3DNhl%eQ| zPt~?ayysidO?`th$;Zj!6tTAFt2g$I7=194Eb|hVLw+CtmNNTlU)2O5?c9{ZN-VmZFIlbqyo%LtNs498QfaB5 zb?rXbfUB=E>|Zb)I({FsdhfK5aX24nuKS1-k8--ddrZRa%3Y3+CinqD)1NX<_1>U` z5ssX^>3_!fxFpU1Ku!S02?O!&RHNiznWz z_!=5s0Sp^R<;?dlu070nP%D2mtV;vmseqCDSVA&`t*v=QSHIF+)lPg{3? z$#j!}WVl}(@n73(|6!cwHze?#L4+^z0Rcsb!p%c)JYK>(F&#JnkkSMEK5C%BVKt&r zl6MO-91(EnIvk&;+j*GMf`q2hnWuw8KGue!p@*iK9?{P=2z!whF!!ya7L@3roU@)l zyirgqb3k@l^KWaQF@5+lASP*`W!~Hs47Sw@dqhvZl)GQ^24UQH@=u1MKdbsD1Hd)1 zmK&J3O45&vP#I`a230iN`!H<;p}tZOgahid6*U^qXu27F(uT3b3x`pemcsMeuuBtB zuB6#$Jm3H;ynBrj_Ej53m1+=3H*O-G7K}32W9Bt8wUWb(kR11~w+k;3u5C|vz!i+f zrSOCLlm4lAAd6t;N?I0M9T9B0{ePRvKo9=Qca|br@432YnaBGNi5~<=eBFOlQz-`E zuyAKCFhEo3f2+}WG;<@W#e?PvkT&9s&N>Uc7BiHgZB7mz5*K*HNY)^LG~2c7AG>)G z{|K795IoX9#Db_cc|@R=KDM9!Xax&2I>ze%>veetu}c%N$I5dq#v*?nFBj7?=a!qw z%i;mA(ncqerp2Y626s5M_Mk8$+LHK0`ffKsTD|Yu+u<*WXDe(*p!{j6U0x0kh){N^ zcMjbZ(Dn-NAGFKjZ+gz34>W^K{+l#ol6FBqBLq?Jwm+D8$Mzx?jAQK$h%P2LKK*T{ z$o+0YCWEm~EXjGM1-@lbj3kxbow4$jEgn9;pbvqjN zn~W1fkmjdjM&M7eAip`NjY+WZPDB?r3fL^YHsLnr@drhA6iea4XDiTuym7AjB z)JuQl6`9p3k>vc$VL(WAjRbz5En@TVQ}|&mFdY+0DD-KGFI)q!1|px1c^=$x-pV=f zh`Bh+Fhz5H^5G=vB#rr3I#?`Ik_3~T@wjYu+W>lt-^7wH1_Rkg@Puz3*eF~W^THdR z7cpSefzvH>Sx4^+%)vGDK7ZQ%rZm7_U>YEw74O>4U!!>%eh>{$q$c7Yn$|m~h_1zj z$E#%CP=*1U_DeoaB*n100sn7;Yfim=M6^{uq34yl4g3}?w7Dt6rvP?CQ8*MqY`hj5 zRX8cSNv@J*s=@$eExCaZAD8i0HCFImwK3mF?Z!C(n?@hA4p#Pp-0ce&)`>?n0q`&OY|iSNfUM#8(=vOa_f)OD zZn8N5NHq!BAM{z6s{Wf3bj3zhNHs>AcVxlKg7n57xoL{JdOvW^0Ai{E@tWHajOj5E zy17|iR0IMrR-^7Hdvhp_^yXY%!17E376$+=GMcnKiZ{I$7*$Zb)E3j*Qya+Ms7M0) zQKNdvf9inA*81cHx$sx}IeOeo3_ju2&-xzy_(TM-M4dIC+~<@r=DA^N`e1+c?9gN> z7$4c-A6?<7zWnQo=M4N{5MW1Zk%*y89TfL_Vv#0p93{DQ{k4dx;Fa#kQ&{i2d=Jwj z13-7!OwPsJxWX$IJ2$bdm=qUv{`W~o#Dmfv6sdUoqTC?u!xf>j=-sWVYN(t1w45=` zy0*^keNXJ+pn}*|r~rYOzumugCC+m$t2YTaY%eY$G&d(e7QYKY_dx#ORN=ACcLEcn zC_1e+0!paE47gJKGjw-f2KPAbMdC?FHfE%D1dc6B~PWfK#gF|s&G9(P8s3glDhij5WZR?|LD^#;e8WIFFAU?X>q%G3cvbJ;x@P~ z2^&2$W05sD&*oR(Dcts0zAX{OyhAZFek^DYRER%N9pjMN>?Bmvp9JYMkva4v(ZqC< zyt4wVe}-#u$mT@}dpxeEuK~Bt%Cw^3u8b;kyTXlr^>yG@sBp`CZ{#t^pBLrqf6SI* zZv1&n(oa9aWJ$4sUZW&vnamts`$u?y6~@vX=AkAfdZ@#XqXJZ)h(tWXH z6O^OY&b0gDYm(t!(;p>N(N3zG>>*OAOmUESlEroB1E5HD+{7ZFDl%}V>m*bTOdLff zaF@o}$GN8Kv(qVRL+{k!qn?|qi?Y}Z-4E4xjUHHZUgNGgq*ww?;ThOiOYEjvwM zKeEPMH54>)lFM{ALVVR)(hFA!bkiJGNBt3 Date: Wed, 6 Jan 2021 12:08:18 +0100 Subject: [PATCH 21/21] added comments --- .../nextlocation/fragments/HomeFragment.java | 83 +++++++++++++++---- 1 file changed, 69 insertions(+), 14 deletions(-) diff --git a/app/src/main/java/com/a1/nextlocation/fragments/HomeFragment.java b/app/src/main/java/com/a1/nextlocation/fragments/HomeFragment.java index 4a8ca4a..1b8f2e6 100644 --- a/app/src/main/java/com/a1/nextlocation/fragments/HomeFragment.java +++ b/app/src/main/java/com/a1/nextlocation/fragments/HomeFragment.java @@ -68,8 +68,6 @@ public class HomeFragment extends Fragment implements LocationListener { Manifest.permission.ACCESS_FINE_LOCATION, // WRITE_EXTERNAL_STORAGE is required in order to show the map Manifest.permission.WRITE_EXTERNAL_STORAGE); -// roadManager = new MapQuestRoadManager(MAPQUEST_API_KEY); -// roadManager.addRequestOption("routeType=foot-walking"); color = requireContext().getColor(R.color.red); } @@ -80,12 +78,14 @@ public class HomeFragment extends Fragment implements LocationListener { View view = inflater.inflate(R.layout.fragment_home, container, false); + // set up the location list button this.imageButton = view.findViewById(R.id.location_list_button); this.imageButton.setOnClickListener(v -> { LocationFragment locationFragment = new LocationFragment(); ((FragmentActivity) view.getContext()).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_layout, locationFragment).addToBackStack(null).commit(); }); + // set up the route stop button stopButton = view.findViewById(R.id.home_stop_route_button); stopButton.setOnClickListener(v -> { RouteHandler.INSTANCE.finishRoute(); @@ -107,18 +107,15 @@ public class HomeFragment extends Fragment implements LocationListener { return view; } + /** + * callback method that gets called when there are new directions available in the form of a {@link DirectionsResult} object. + * @param directionsResult the directions received from the api + */ private void onDirectionsAvailable(DirectionsResult directionsResult) { Log.d(TAG, "onDirectionsAvailable: got result! " + directionsResult); ArrayList geoPoints = directionsResult.getGeoPoints(); roadOverlay = new Polyline(); roadOverlay.setPoints(geoPoints); - - // this is for mapquest, but it gives a "no value for guidancelinkcollection" error and google has never heard of that -// GeoPoint[] gp = directionsResult.getStartAndEndPoint(); -// ArrayList arrayList = new ArrayList<>(Arrays.asList(gp)); -// Road road = roadManager.getRoad(arrayList); -// roadOverlay = RoadManager.buildRoadOverlay(road); - roadOverlay.setColor(color); @@ -175,13 +172,13 @@ public class HomeFragment extends Fragment implements LocationListener { try { + // request location updates for the distance checking locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this); + // get the current location and set it as center Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); - if (currentLocation == null) { - currentLocation = location; - } + if (currentLocation == null) currentLocation = location; if (location != null) { GeoPoint start = new GeoPoint(location.getLatitude(), location.getLongitude()); @@ -204,6 +201,9 @@ public class HomeFragment extends Fragment implements LocationListener { } + /** + * displays the route that is currently being followed as a red line + */ private void displayRoute() { if (RouteHandler.INSTANCE.isFollowingRoute()) { @@ -222,30 +222,54 @@ public class HomeFragment extends Fragment implements LocationListener { } } + /** + * adds the locations of the current route to the map. If there is no current route, show all locations + */ private void addLocations() { + // get the locations of the current route or all locations List locations = RouteHandler.INSTANCE.isFollowingRoute() ? RouteHandler.INSTANCE.getCurrentRoute().getLocations() : LocationListManager.INSTANCE.getLocationList(); final ArrayList items = new ArrayList<>(locations.size()); + // marker icon Drawable marker = ContextCompat.getDrawable(requireContext(), R.drawable.ic_baseline_location_on_24); marker.setAlpha(255); marker.setTint(getResources().getColor(R.color.primaryColour)); + + // add all locations to the overlay itemss for (com.a1.nextlocation.data.Location location : locations) { OverlayItem item = new OverlayItem(location.getName(), location.getDescription(), location.convertToGeoPoint()); item.setMarker(marker); items.add(item); } + + // create the overlay that will hold all locations and add listeners allLocationsOverlay = new ItemizedIconOverlay(items, new ItemizedIconOverlay.OnItemGestureListener() { + /** + * on sinlge click, navigate to that location's detail fragment + * @param index the index in the location list + * @param item the item that was clicked + * @return true + */ @Override public boolean onItemSingleTapUp(int index, OverlayItem item) { com.a1.nextlocation.data.Location clicked = locations.get(index); requireActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragment_layout, new LocationDetailFragment(clicked)).commit(); - return false; + return true; } + /** + * on item long press, show that location's name in a toast message + * @param index the index in the location list + * @param item the item that was clicked + * @return true + */ @Override public boolean onItemLongPress(int index, OverlayItem item) { com.a1.nextlocation.data.Location clicked = locations.get(index); Toast.makeText(requireContext(), clicked.getName(), Toast.LENGTH_SHORT).show(); + + // create a route to the clicked location, didn't work and didn't have enough time to make it work ¯\_(ツ)_/¯ + // Route route = new Route("Route to " + clicked.getName()); // route.addLocation(new com.a1.nextlocation.data.Location("Current location",currentLocation.getLatitude(),currentLocation.getLongitude(),"your location",null)); // route.addLocation(clicked); @@ -254,11 +278,17 @@ public class HomeFragment extends Fragment implements LocationListener { } }, requireContext()); + // add the overlay to the map mapView.getOverlays().add(allLocationsOverlay); Log.d(TAG, "addLocations: successfully added locations"); } + /** + * @author Ricky + * request the permissions needed for location and network, made by Ricky + * @param permissions tbe permissions we want to ask + */ private void requestPermissionsIfNecessary(String... permissions) { ArrayList permissionsToRequest = new ArrayList<>(); if (this.getContext() != null) @@ -277,13 +307,18 @@ public class HomeFragment extends Fragment implements LocationListener { } } + /** + * location callback that gets called each time the location is updated. It is used for updating the distance walked and checking if there are locations you have visited + * @param location the new location + */ @Override public void onLocationChanged(@NonNull Location location) { + // calculate the distance walked double distance = currentLocation.distanceTo(location); // in meters StaticData.INSTANCE.addDistance(distance); currentLocation = location; - //new thread because we don't want the main thread to hang + //new thread because we don't want the main thread to hang, this method gets called a lot Thread t = new Thread(() -> { for (com.a1.nextlocation.data.Location l : LocationListManager.INSTANCE.getLocationList()) { if (com.a1.nextlocation.data.Location.getDistance(currentLocation.getLatitude(), currentLocation.getLongitude(), l.getLat(), l.getLong()) < 10) { @@ -295,6 +330,8 @@ public class HomeFragment extends Fragment implements LocationListener { t.start(); } + // empty override methods for the LocationListener + @Override public void onStatusChanged(String provider, int status, Bundle extras) { @@ -309,4 +346,22 @@ public class HomeFragment extends Fragment implements LocationListener { public void onProviderDisabled(@NonNull String provider) { } + + /** + * method that gets called when the app gets paused + */ + @Override + public void onPause() { + super.onPause(); + mapView.onPause(); + } + + /** + * method that gets called when the app gets resumed + */ + @Override + public void onResume() { + super.onResume(); + mapView.onResume(); + } } \ No newline at end of file