-
Notifications
You must be signed in to change notification settings - Fork 134
/
SearchExample.java
414 lines (345 loc) · 15.8 KB
/
SearchExample.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
/*
* Copyright (C) 2019-2021 HERE Europe B.V.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
* License-Filename: LICENSE
*/
package com.here.search;
import android.content.Context;
import android.net.ConnectivityManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.widget.Toast;
import com.here.sdk.core.Anchor2D;
import com.here.sdk.core.CustomMetadataValue;
import com.here.sdk.core.GeoBox;
import com.here.sdk.core.GeoCoordinates;
import com.here.sdk.core.LanguageCode;
import com.here.sdk.core.Metadata;
import com.here.sdk.core.Point2D;
import com.here.sdk.core.errors.InstantiationErrorException;
import com.here.sdk.gestures.GestureState;
import com.here.sdk.mapview.MapCamera;
import com.here.sdk.mapview.MapImage;
import com.here.sdk.mapview.MapImageFactory;
import com.here.sdk.mapview.MapMarker;
import com.here.sdk.mapview.MapView;
import com.here.sdk.mapview.MapViewBase;
import com.here.sdk.mapview.PickMapItemsResult;
import com.here.sdk.search.Address;
import com.here.sdk.search.AddressQuery;
import com.here.sdk.search.OfflineSearchEngine;
import com.here.sdk.search.Place;
import com.here.sdk.search.SearchCallback;
import com.here.sdk.search.SearchEngine;
import com.here.sdk.search.SearchError;
import com.here.sdk.search.SearchOptions;
import com.here.sdk.search.SuggestCallback;
import com.here.sdk.search.Suggestion;
import com.here.sdk.search.TextQuery;
import java.util.ArrayList;
import java.util.List;
public class SearchExample {
private static final String LOG_TAG = SearchExample.class.getName();
private final Context context;
private final MapView mapView;
private final MapCamera camera;
private final List<MapMarker> mapMarkerList = new ArrayList<>();
private SearchEngine searchEngine;
private OfflineSearchEngine offlineSearchEngine;
public SearchExample(Context context, MapView mapView) {
this.context = context;
this.mapView = mapView;
camera = mapView.getCamera();
double distanceInMeters = 1000 * 10;
camera.lookAt(new GeoCoordinates(52.520798, 13.409408), distanceInMeters);
try {
searchEngine = new SearchEngine();
} catch (InstantiationErrorException e) {
throw new RuntimeException("Initialization of SearchEngine failed: " + e.error.name());
}
try {
// Allows to search on already downloaded or cached map data.
offlineSearchEngine = new OfflineSearchEngine();
} catch (InstantiationErrorException e) {
throw new RuntimeException("Initialization of OfflineSearchEngine failed: " + e.error.name());
}
setTapGestureHandler();
setLongPressGestureHandler();
Toast.makeText(context,"Long press on map to get the address for that position using reverse geocoding.", Toast.LENGTH_LONG).show();
}
public void onSearchButtonClicked() {
// Search for "Pizza" and show the results on the map.
searchExample();
// Search for auto suggestions and log the results to the console.
autoSuggestExample();
}
public void onGeocodeButtonClicked() {
// Search for the location that belongs to an address and show it on the map.
geocodeAnAddress();
}
private void searchExample() {
String searchTerm = "Pizza";
Toast.makeText(context,"Searching in viewport: " + searchTerm, Toast.LENGTH_LONG).show();
searchInViewport(searchTerm);
}
private void geocodeAnAddress() {
// Set map to expected location.
GeoCoordinates geoCoordinates = new GeoCoordinates(52.53086, 13.38469);
camera.flyTo(geoCoordinates);
String queryString = "Invalidenstraße 116, Berlin";
Toast.makeText(context,"Finding locations for: " + queryString
+ ". Tap marker to see the coordinates. Check the logs for the address.", Toast.LENGTH_LONG).show();
geocodeAddressAtLocation(queryString, geoCoordinates);
}
private void setTapGestureHandler() {
mapView.getGestures().setTapListener(touchPoint -> pickMapMarker(touchPoint));
}
private void setLongPressGestureHandler() {
mapView.getGestures().setLongPressListener((gestureState, touchPoint) -> {
if (gestureState == GestureState.BEGIN) {
GeoCoordinates geoCoordinates = mapView.viewToGeoCoordinates(touchPoint);
if (geoCoordinates == null) {
return;
}
addPoiMapMarker(geoCoordinates);
getAddressForCoordinates(geoCoordinates);
}
});
}
private void getAddressForCoordinates(GeoCoordinates geoCoordinates) {
int maxItems = 1;
SearchOptions reverseGeocodingOptions = new SearchOptions(LanguageCode.EN_GB, maxItems);
if (isDeviceConnected()) {
searchEngine.search(geoCoordinates, reverseGeocodingOptions, addressSearchCallback);
} else {
offlineSearchEngine.search(geoCoordinates, reverseGeocodingOptions, addressSearchCallback);
}
}
private SearchCallback addressSearchCallback = new SearchCallback() {
@Override
public void onSearchCompleted(@Nullable SearchError searchError, @Nullable List<Place> list) {
if (searchError != null) {
showDialog("Reverse geocoding", "Error: " + searchError.toString());
return;
}
// If error is null, list is guaranteed to be not empty.
showDialog("Reverse geocoded address:", list.get(0).getAddress().addressText);
}
};
private void pickMapMarker(final Point2D point2D) {
float radiusInPixel = 2;
mapView.pickMapItems(point2D, radiusInPixel, new MapViewBase.PickMapItemsCallback() {
@Override
public void onPickMapItems(@Nullable PickMapItemsResult pickMapItemsResult) {
if (pickMapItemsResult == null) {
return;
}
List<MapMarker> mapMarkerList = pickMapItemsResult.getMarkers();
if (mapMarkerList.size() == 0) {
return;
}
MapMarker topmostMapMarker = mapMarkerList.get(0);
Metadata metadata = topmostMapMarker.getMetadata();
if (metadata != null) {
CustomMetadataValue customMetadataValue = metadata.getCustomValue("key_search_result");
if (customMetadataValue != null) {
SearchResultMetadata searchResultMetadata = (SearchResultMetadata) customMetadataValue;
String title = searchResultMetadata.searchResult.getTitle();
String vicinity = searchResultMetadata.searchResult.getAddress().addressText;
showDialog("Picked Search Result",title + ". Vicinity: " + vicinity);
return;
}
}
showDialog("Picked Map Marker",
"Geographic coordinates: " +
topmostMapMarker.getCoordinates().latitude + ", " +
topmostMapMarker.getCoordinates().longitude);
}
});
}
private void searchInViewport(String queryString) {
clearMap();
GeoBox viewportGeoBox = getMapViewGeoBox();
TextQuery query = new TextQuery(queryString, viewportGeoBox);
int maxItems = 30;
SearchOptions searchOptions = new SearchOptions(LanguageCode.EN_US, maxItems);
if (isDeviceConnected()) {
searchEngine.search(query, searchOptions, querySearchCallback);
} else {
offlineSearchEngine.search(query, searchOptions, querySearchCallback);
}
}
private SearchCallback querySearchCallback = new SearchCallback() {
@Override
public void onSearchCompleted(@Nullable SearchError searchError, @Nullable List<Place> list) {
if (searchError != null) {
showDialog("Search", "Error: " + searchError.toString());
return;
}
// If error is null, list is guaranteed to be not empty.
showDialog("Search", "Results: " + list.size());
// Add new marker for each search result on map.
for (Place searchResult : list) {
Metadata metadata = new Metadata();
metadata.setCustomValue("key_search_result", new SearchResultMetadata(searchResult));
// Note: getGeoCoordinates() may return null only for Suggestions.
addPoiMapMarker(searchResult.getGeoCoordinates(), metadata);
}
}
};
private static class SearchResultMetadata implements CustomMetadataValue {
public final Place searchResult;
public SearchResultMetadata(Place searchResult) {
this.searchResult = searchResult;
}
@NonNull
@Override
public String getTag() {
return "SearchResult Metadata";
}
}
private final SuggestCallback autosuggestCallback = new SuggestCallback() {
@Override
public void onSuggestCompleted(@Nullable SearchError searchError, @Nullable List<Suggestion> list) {
if (searchError != null) {
Log.d(LOG_TAG, "Autosuggest Error: " + searchError.name());
return;
}
// If error is null, list is guaranteed to be not empty.
Log.d(LOG_TAG, "Autosuggest results: " + list.size());
for (Suggestion autosuggestResult : list) {
String addressText = "Not a place.";
Place place = autosuggestResult.getPlace();
if (place != null) {
addressText = place.getAddress().addressText;
}
Log.d(LOG_TAG, "Autosuggest result: " + autosuggestResult.getTitle() +
" addressText: " + addressText);
}
}
};
// Note: Suggestions are not available for the OfflineSearchEngine.
private void autoSuggestExample() {
GeoCoordinates centerGeoCoordinates = getMapViewCenter();
int maxItems = 5;
SearchOptions searchOptions = new SearchOptions(LanguageCode.EN_US, maxItems);
// Simulate a user typing a search term.
searchEngine.suggest(
new TextQuery("p", // User typed "p".
centerGeoCoordinates),
searchOptions,
autosuggestCallback);
searchEngine.suggest(
new TextQuery("pi", // User typed "pi".
centerGeoCoordinates),
searchOptions,
autosuggestCallback);
searchEngine.suggest(
new TextQuery("piz", // User typed "piz".
centerGeoCoordinates),
searchOptions,
autosuggestCallback);
}
private void geocodeAddressAtLocation(String queryString, GeoCoordinates geoCoordinates) {
clearMap();
AddressQuery query = new AddressQuery(queryString, geoCoordinates);
int maxItems = 30;
SearchOptions options = new SearchOptions(LanguageCode.DE_DE, maxItems);
if (isDeviceConnected()) {
searchEngine.search(query, options, geocodeAddressSearchCallback);
} else {
offlineSearchEngine.search(query, options, geocodeAddressSearchCallback);
}
}
private SearchCallback geocodeAddressSearchCallback = new SearchCallback() {
@Override
public void onSearchCompleted(SearchError searchError, List<Place> list) {
if (searchError != null) {
showDialog("Geocoding", "Error: " + searchError.toString());
return;
}
for (Place geocodingResult : list) {
// Note: getGeoCoordinates() may return null only for Suggestions.
GeoCoordinates geoCoordinates = geocodingResult.getGeoCoordinates();
Address address = geocodingResult.getAddress();
String locationDetails = address.addressText
+ ". GeoCoordinates: " + geoCoordinates.latitude
+ ", " + geoCoordinates.longitude;
Log.d(LOG_TAG, "GeocodingResult: " + locationDetails);
addPoiMapMarker(geoCoordinates);
}
showDialog("Geocoding result","Size: " + list.size());
}
};
private void addPoiMapMarker(GeoCoordinates geoCoordinates) {
MapMarker mapMarker = createPoiMapMarker(geoCoordinates);
mapView.getMapScene().addMapMarker(mapMarker);
mapMarkerList.add(mapMarker);
}
private void addPoiMapMarker(GeoCoordinates geoCoordinates, Metadata metadata) {
MapMarker mapMarker = createPoiMapMarker(geoCoordinates);
mapMarker.setMetadata(metadata);
mapView.getMapScene().addMapMarker(mapMarker);
mapMarkerList.add(mapMarker);
}
private MapMarker createPoiMapMarker(GeoCoordinates geoCoordinates) {
MapImage mapImage = MapImageFactory.fromResource(context.getResources(), R.drawable.poi);
return new MapMarker(geoCoordinates, mapImage, new Anchor2D(0.5F, 1));
}
private GeoCoordinates getMapViewCenter() {
GeoCoordinates centerGeoCoordinates = mapView.viewToGeoCoordinates(new Point2D(mapView.getWidth() / 2, mapView.getHeight() / 2));
if (centerGeoCoordinates == null) {
// Should never happen for center coordinates.
throw new RuntimeException("CenterGeoCoordinates are null");
}
return centerGeoCoordinates;
}
private GeoBox getMapViewGeoBox() {
int mapViewWidthInPixels = mapView.getWidth();
int mapViewHeightInPixels = mapView.getHeight();
Point2D bottomLeftPoint2D = new Point2D(0, mapViewHeightInPixels);
Point2D topRightPoint2D = new Point2D(mapViewWidthInPixels, 0);
GeoCoordinates southWestCorner = mapView.viewToGeoCoordinates(bottomLeftPoint2D);
GeoCoordinates northEastCorner = mapView.viewToGeoCoordinates(topRightPoint2D);
if (southWestCorner == null || northEastCorner == null) {
throw new RuntimeException("GeoBox creation failed, corners are null.");
}
// Note: This algorithm assumes an unrotated map view.
return new GeoBox(southWestCorner, northEastCorner);
}
private void clearMap() {
for (MapMarker mapMarker : mapMarkerList) {
mapView.getMapScene().removeMapMarker(mapMarker);
}
mapMarkerList.clear();
}
// Note: This method checks if the device is offline or not, but it does not check if the device is
// able to initiate a connection to the internet.
private boolean isDeviceConnected() {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
return connectivityManager.getActiveNetworkInfo() != null;
}
private void showDialog(String title, String message) {
AlertDialog.Builder builder =
new AlertDialog.Builder(context);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
}