-
Notifications
You must be signed in to change notification settings - Fork 3
/
Navigation.java
424 lines (387 loc) · 15.8 KB
/
Navigation.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
package com.kode.navigation;
import static com.google.appinventor.components.runtime.util.GeometryUtil.isValidLatitude;
import static com.google.appinventor.components.runtime.util.GeometryUtil.isValidLongitude;
import static com.google.appinventor.components.runtime.util.YailDictionary.ALL;
import static java.util.Arrays.asList;
import android.util.Log;
import com.google.appinventor.components.annotations.UsesLibraries;
import com.google.appinventor.components.annotations.UsesPermissions;
import com.google.appinventor.components.annotations.DesignerComponent;
import com.google.appinventor.components.annotations.DesignerProperty;
import com.google.appinventor.components.annotations.SimpleObject;
import com.google.appinventor.components.annotations.SimpleFunction;
import com.google.appinventor.components.annotations.SimpleEvent;
import com.google.appinventor.components.annotations.SimpleProperty;
import com.google.appinventor.components.common.ComponentCategory;
import com.google.appinventor.components.runtime.AndroidNonvisibleComponent;
import com.google.appinventor.components.runtime.AndroidViewComponent;
import com.google.appinventor.components.runtime.ComponentContainer;
import com.google.appinventor.components.runtime.EventDispatcher;
import com.google.appinventor.components.common.YaVersion;
import com.google.appinventor.components.runtime.util.AsynchUtil;
import com.google.appinventor.components.runtime.util.ErrorMessages;
import com.google.appinventor.components.runtime.util.GeoJSONUtil;
import com.google.appinventor.components.runtime.util.JsonUtil;
import com.google.appinventor.components.runtime.util.MapFactory.MapFeature;
import com.google.appinventor.components.runtime.util.YailDictionary;
import com.google.appinventor.components.runtime.util.YailList;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import org.json.JSONException;
import org.osmdroid.util.GeoPoint;
@SuppressWarnings("TryFinallyCanBeTryWithResources")
@DesignerComponent(version = 1,
category = ComponentCategory.EXTENSION,
description = "Use this extension to simply add the power to get directions directly from the app<br>Source code by: app invenotr",
nonVisible = true,
iconName = "https://i.imgur.com/uxlvdZ7.png")
@UsesPermissions(permissionNames = "android.permission.INTERNET")
@UsesLibraries({"osmdroid.jar"})
@SimpleObject(external = true)
public class navigation extends AndroidNonvisibleComponent{
private static final String TAG = "Navigation";
public static final String OPEN_ROUTE_SERVICE_URL =
"https://api.openrouteservice.org/v2/directions/";
private String apiKey;
private GeoPoint startLocation;
private GeoPoint endLocation;
private TransportMethod method;
private String serviceUrl = OPEN_ROUTE_SERVICE_URL;
private String language = "en";
private YailDictionary lastResponse = YailDictionary.makeDictionary();
enum TransportMethod {
DEFAULT ("foot-walking"),
DRIVING ("driving-car"),
CYCLING ("cycling-regular"),
WALKING ("foot-walking"),
WHEELCHAIR ("wheelchair");
private final String method;
TransportMethod(String method) {
this.method = method;
}
private String method() {
return method;
}
}
/**
* Creates a Navigation component.
*
* @param container container, component will be placed in
*/
public navigation(ComponentContainer container) {
super(container.$form());
apiKey = "";
startLocation = new GeoPoint(0.0, 0.0);
endLocation = new GeoPoint(0.0, 0.0);
method = TransportMethod.DEFAULT;
}
/**
* Request directions from the routing service using the values of {@link #StartLatitude()},
* {@link #StartLongitude()}, {@link #EndLatitude()}, and {@link #EndLongitude()}. On success,
* the {@link #GotDirections(YailList, YailList, double, double)} event block will run. If an
* error occurs, the error will be reported via the
* [`Screen's ErrorOccurred`](userinterface.html#Screen.ErrorOccurred) event.
*/
@SimpleFunction(description = "Request directions from the routing service.")
public void RequestDirections() {
if (apiKey.equals("")) {
form.dispatchErrorOccurredEvent(this, "Authorization", ErrorMessages.ERROR_INVALID_API_KEY);
return;
}
final GeoPoint startLocation = this.startLocation;
final GeoPoint endLocation = this.endLocation;
final TransportMethod method = this.method;
AsynchUtil.runAsynchronously(new Runnable() {
@SuppressWarnings("TryWithIdenticalCatches")
@Override
public void run() {
try {
performRequest(startLocation, endLocation, method);
} catch (IOException e) {
form.dispatchErrorOccurredEvent(navigation.this, "RequestDirections",
ErrorMessages.ERROR_DEFAULT);
} catch (JSONException je) {
form.dispatchErrorOccurredEvent(navigation.this, "RequestDirections",
ErrorMessages.ERROR_DEFAULT);
}
}
});
}
/**
* Reserved for future use in case we decide to run our own service some day.
*/
@SimpleProperty(userVisible = false)
public void ServiceURL(String url) {
this.serviceUrl = url;
}
/**
* API Key for Open Route Service. Obtain an API key at
* [https://openrouteservice.org](https://openrouteservice.org).
*
* @param key the API key to use for authentication requests
*/
@DesignerProperty
@SimpleProperty(description = "API Key for Open Route Service.")
public void ApiKey(String key) {
apiKey = key;
}
@DesignerProperty(defaultValue = "0.0")
@SimpleProperty
public void StartLatitude(double latitude) {
if (isValidLatitude(latitude)) {
startLocation.setLatitude(latitude);
} else {
getDispatchDelegate().dispatchErrorOccurredEvent(this, "StartLatitude",
ErrorMessages.ERROR_INVALID_LATITUDE, latitude);
}
}
@SimpleProperty(description = "The latitude of the start location.")
public double StartLatitude() {
return startLocation.getLatitude();
}
@DesignerProperty(defaultValue = "0.0")
@SimpleProperty
public void StartLongitude(double longitude) {
if (isValidLongitude(longitude)) {
startLocation.setLongitude(longitude);
} else {
getDispatchDelegate().dispatchErrorOccurredEvent(this, "StartLongitude",
ErrorMessages.ERROR_INVALID_LONGITUDE, longitude);
}
}
@SimpleProperty(description = "The longitude of the start location.")
public double StartLongitude() {
return startLocation.getLongitude();
}
@SimpleProperty(description = "Set the start location.")
public void StartLocation(MapFeature feature) {
GeoPoint point = feature.getCentroid();
double latitude = point.getLatitude();
double longitude = point.getLongitude();
if (!isValidLatitude(latitude)) {
getDispatchDelegate().dispatchErrorOccurredEvent(this, "SetStartLocation",
ErrorMessages.ERROR_INVALID_LATITUDE, latitude);
} else if (!isValidLongitude(longitude)) {
getDispatchDelegate().dispatchErrorOccurredEvent(this, "SetStartLocation",
ErrorMessages.ERROR_INVALID_LONGITUDE, longitude);
} else {
startLocation.setCoords(latitude, longitude);
}
}
@DesignerProperty(defaultValue = "0.0")
@SimpleProperty
public void EndLatitude(double latitude) {
if (isValidLatitude(latitude)) {
endLocation.setLatitude(latitude);
} else {
getDispatchDelegate().dispatchErrorOccurredEvent(this, "EndLatitude",
ErrorMessages.ERROR_INVALID_LATITUDE, latitude);
}
}
@SimpleProperty(description = "The latitude of the end location.")
public double EndLatitude() {
return endLocation.getLatitude();
}
@DesignerProperty(defaultValue = "0.0")
@SimpleProperty
public void EndLongitude(double longitude) {
if (isValidLongitude(longitude)) {
endLocation.setLongitude(longitude);
} else {
getDispatchDelegate().dispatchErrorOccurredEvent(this, "EndLongitude",
ErrorMessages.ERROR_INVALID_LONGITUDE, longitude);
}
}
@SimpleProperty(description = "The longitude of the end location.")
public double EndLongitude() {
return endLocation.getLongitude();
}
@SimpleProperty
public String TransportationMethod() {
return method.method();
}
/**
* The transportation method used for determining the route. Valid options are:
*
* - `foot-walking`: Route based on walking paths
* - `driving-car`: Route based on vehicle paths
* - `cycling-regular`: Route based on bicycle paths
* - `wheelchair`: Route based on wheelchair accessible paths
*
* @param method the method to use
*/
@DesignerProperty(defaultValue = "foot-walking")
@SimpleProperty(description = "The transportation method used for determining the route.")
public void TransportationMethod(String method) {
for (TransportMethod t : TransportMethod.values()) {
if (method.equals(t.method())) {
this.method = t;
}
}
}
@SimpleProperty(description = "Set the end location.")
public void EndLocation(MapFeature feature) {
GeoPoint point = feature.getCentroid();
double latitude = point.getLatitude();
double longitude = point.getLongitude();
if (!isValidLatitude(latitude)) {
getDispatchDelegate().dispatchErrorOccurredEvent(this, "SetEndLocation",
ErrorMessages.ERROR_INVALID_LATITUDE, latitude);
} else if (!isValidLongitude(longitude)) {
getDispatchDelegate().dispatchErrorOccurredEvent(this, "SetEndLocation",
ErrorMessages.ERROR_INVALID_LONGITUDE, longitude);
} else {
endLocation.setCoords(latitude, longitude);
}
}
/**
* The language to use for textual directions. Default is "en" for English.
*
* @param language the language to use for generating directions
*/
@SimpleProperty(description = "The language to use for textual directions.")
@DesignerProperty(defaultValue = "en")
public void Language(String language) {
this.language = language;
}
@SimpleProperty
public String Language() {
return language;
}
/**
* The raw response from the server. This can be used to access more details beyond what the
* {@link #GotDirections(YailList, YailList, double, double)} event provides.
*
* @return the content of the response
*/
@SimpleProperty(description = "Content of the last response as a dictionary.")
public YailDictionary ResponseContent() {
return lastResponse;
}
/**
* Event indicating that a request has finished and has returned data. The following parameters
* are provided:
*
* - `directions`: A list of text directions, such as "Turn left at Massachusetts Avenue".
* - `points`: A list of (latitude, longitude) points that represent the path to take. This can
* be passed to {@link LineString#Points(YailList)} to draw the line on a {@link Map}.
* - `distance`: Estimated distance for the route, in meters.
* - `duration`: Estimated duration for the route, in seconds.
*
* @param directions a list of navigation statements
* @param points a YailList containing the coordinates of a geojson LineString of the path
* @param distance the distance of the route, in meters
* @param duration the estimated duration to travel the route, in seconds
*/
@SimpleEvent(description = "Event triggered when the Openrouteservice returns the directions.")
public void GotDirections(YailList directions, YailList points, double distance,
double duration) {
Log.d(TAG, "GotDirections");
EventDispatcher.dispatchEvent(this, "GotDirections", directions, points, distance, duration);
}
// MARK: Private implementation
private void performRequest(GeoPoint start, GeoPoint end, TransportMethod method)
throws IOException, JSONException {
final String finalURL = serviceUrl + method.method() + "/geojson/";
URL url = new URL(finalURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection.setRequestMethod("POST");
connection.setRequestProperty("Authorization", apiKey);
try {
String coords = "{\"coordinates\": "
+ JsonUtil.getJsonRepresentation(getCoordinates(start, end)) + ", \"language\": \""
+ language + "\"}";
byte[] postData = coords.getBytes("UTF-8");
connection.setFixedLengthStreamingMode(postData.length);
BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream());
try {
out.write(postData, 0, postData.length);
out.flush();
} finally {
out.close();
}
if (connection.getResponseCode() != 200) {
form.dispatchErrorOccurredEvent(this, "RequestDirections",
ErrorMessages.ERROR_ROUTING_SERVICE_ERROR, connection.getResponseCode(),
connection.getResponseMessage());
return;
}
final String geoJson = getResponseContent(connection);
Log.d(TAG, geoJson);
final YailDictionary response = (YailDictionary) JsonUtil.getObjectFromJson(geoJson, true);
YailList features = (YailList) response.get("features");
if (features.size() > 0) {
YailDictionary feature = (YailDictionary) features.getObject(0);
YailDictionary summary =
(YailDictionary) feature.getObjectAtKeyPath(asList("properties", "summary"));
final double distance = (Double) summary.get("distance");
final double duration = (Double) summary.get("duration");
final YailList directions = YailList.makeList(getDirections(feature));
final YailList coordinates = getLineStringCoords(feature);
form.runOnUiThread(new Runnable() {
@Override
public void run() {
lastResponse = response;
GotDirections(directions, coordinates, distance, duration);
}
});
} else {
// No response
form.dispatchErrorOccurredEvent(this, "RequestDirections",
ErrorMessages.ERROR_NO_ROUTE_FOUND);
}
} catch (Exception e) {
form.dispatchErrorOccurredEvent(this, "RequestDirections",
ErrorMessages.ERROR_UNABLE_TO_REQUEST_DIRECTIONS, e.getMessage());
e.printStackTrace();
} finally {
connection.disconnect();
}
}
private static String getResponseContent(HttpURLConnection connection) throws IOException {
String encoding = connection.getContentEncoding();
if (encoding == null) {
encoding = "UTF-8";
}
Log.d(TAG, Integer.toString(connection.getResponseCode()));
InputStreamReader reader = new InputStreamReader(connection.getInputStream(), encoding);
try {
int contentLength = connection.getContentLength();
StringBuilder sb = (contentLength != -1)
? new StringBuilder(contentLength)
: new StringBuilder();
char[] buf = new char[1024];
int read;
while ((read = reader.read(buf)) != -1) {
sb.append(buf, 0, read);
}
return sb.toString();
} finally {
reader.close();
}
}
private Double[][] getCoordinates(GeoPoint startLocation, GeoPoint endLocation) {
Double[][] coords = new Double[2][2];
coords[0][0] = startLocation.getLongitude();
coords[0][1] = startLocation.getLatitude();
coords[1][0] = endLocation.getLongitude();
coords[1][1] = endLocation.getLatitude();
return coords;
}
private YailList getLineStringCoords(YailDictionary feature) {
YailList coords =
(YailList) feature.getObjectAtKeyPath(asList("geometry", "coordinates"));
return GeoJSONUtil.swapCoordinates(coords);
}
private List<?> getDirections(YailDictionary feature) {
return YailDictionary.walkKeyPath(feature,
asList("properties", "segments", ALL, "steps", ALL, "instruction"));
}
}