/
SearchExample.swift
311 lines (256 loc) · 12.4 KB
/
SearchExample.swift
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
/*
* 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
*/
import heresdk
import UIKit
class SearchExample: TapDelegate,
LongPressDelegate {
private var viewController: UIViewController
private var mapView: MapView
private var mapMarkers = [MapMarker]()
private var searchEngine: SearchEngine
init(viewController: UIViewController, mapView: MapView) {
self.viewController = viewController
self.mapView = mapView
let camera = mapView.camera
camera.lookAt(point: GeoCoordinates(latitude: 52.520798, longitude: 13.409408),
distanceInMeters: 1000 * 10)
do {
try searchEngine = SearchEngine()
} catch let engineInstantiationError {
fatalError("Failed to initialize SearchEngine. Cause: \(engineInstantiationError)")
}
mapView.gestures.tapDelegate = self
mapView.gestures.longPressDelegate = self
showDialog(title: "Note", message: "Long press on map to get the address for that position using reverse geocoding.")
}
func onSearchButtonClicked() {
// Search for "Pizza" and show the results on the map.
searchExample()
// Search for auto suggestions and log the results to the console.
autoSuggestExample()
}
func onGeoCodeButtonClicked() {
// Search for the location that belongs to an address and show it on the map.
geocodeAnAddress()
}
private func searchExample() {
let searchTerm = "Pizza"
searchInViewport(queryString: searchTerm)
}
private func searchInViewport(queryString: String) {
clearMap()
let textQuery = TextQuery(queryString, in: getMapViewGeoBox())
let searchOptions = SearchOptions(languageCode: LanguageCode.enUs,
maxItems: 30)
_ = searchEngine.search(textQuery: textQuery,
options: searchOptions,
completion: onSearchCompleted)
}
// Completion handler to receive search results.
func onSearchCompleted(error: SearchError?, items: [Place]?) {
if let searchError = error {
showDialog(title: "Search", message: "Error: \(searchError)")
return
}
// If error is nil, it is guaranteed that the items will not be nil.
showDialog(title: "Search in viewport for: 'Pizza'.",
message: "Found \(items!.count) results.")
// Add a new marker for each search result on map.
for searchResult in items! {
let metadata = Metadata()
metadata.setCustomValue(key: "key_search_result", value: SearchResultMetadata(searchResult))
// Note that geoCoordinates are always set, but can be nil for suggestions only.
addPoiMapMarker(geoCoordinates: searchResult.geoCoordinates!, metadata: metadata)
}
}
private class SearchResultMetadata : CustomMetadataValue {
var searchResult: Place
init(_ searchResult: Place) {
self.searchResult = searchResult
}
func getTag() -> String {
return "SearchResult Metadata"
}
}
private func autoSuggestExample() {
let centerGeoCoordinates = getMapViewCenter()
let autosuggestOptions = SearchOptions(languageCode: LanguageCode.enUs,
maxItems: 5)
// Simulate a user typing a search term.
_ = searchEngine.suggest(textQuery: TextQuery("p", near: centerGeoCoordinates),
options: autosuggestOptions,
completion: onSearchCompleted)
_ = searchEngine.suggest(textQuery: TextQuery("pi", near: centerGeoCoordinates),
options: autosuggestOptions,
completion: onSearchCompleted)
_ = searchEngine.suggest(textQuery: TextQuery("piz", near: centerGeoCoordinates),
options: autosuggestOptions,
completion: onSearchCompleted)
}
// Completion handler to receive auto suggestion results.
func onSearchCompleted(error: SearchError?, items: [Suggestion]?) {
if let searchError = error {
print("Autosuggest Error: \(searchError)")
return
}
// If error is nil, it is guaranteed that the items will not be nil.
print("Autosuggest: Found \(items!.count) result(s).")
for autosuggestResult in items! {
var addressText = "Not a place."
if let place = autosuggestResult.place {
addressText = place.address.addressText
}
print("Autosuggest result: \(autosuggestResult.title), addressText: \(addressText)")
}
}
public func geocodeAnAddress() {
// Set map near to expected location.
let geoCoordinates = GeoCoordinates(latitude: 52.53086, longitude: 13.38469)
mapView.camera.lookAt(point: geoCoordinates, distanceInMeters: 1000 * 5)
let streetName = "Invalidenstraße 116, Berlin"
geocodeAddressAtLocation(queryString: streetName, geoCoordinates: geoCoordinates)
}
private func geocodeAddressAtLocation(queryString: String, geoCoordinates: GeoCoordinates) {
clearMap()
let query = AddressQuery(queryString, near: geoCoordinates)
let geocodingOptions = SearchOptions(languageCode: LanguageCode.deDe,
maxItems: 25)
_ = searchEngine.search(addressQuery: query,
options: geocodingOptions,
completion: onGeocodingCompleted)
}
// Completion handler to receive geocoding results.
func onGeocodingCompleted(error: SearchError?, items: [Place]?) {
if let searchError = error {
showDialog(title: "Geocoding", message: "Error: \(searchError)")
return
}
// If error is nil, it is guaranteed that the items will not be nil.
for geocodingResult in items! {
// Note that geoCoordinates are always set, but can be nil for suggestions only.
let geoCoordinates = geocodingResult.geoCoordinates!
let address = geocodingResult.address
let locationDetails = address.addressText
+ ". Coordinates: \(geoCoordinates.latitude)"
+ ", \(geoCoordinates.longitude)"
showDialog(title: "Geocoding - Locations in viewport for 'Invalidenstraße 116, Berlin':",
message: "Found: \(items!.count) result(s): \(locationDetails)")
self.addPoiMapMarker(geoCoordinates: geoCoordinates)
}
}
// Conforming to TapDelegate protocol.
func onTap(origin: Point2D) {
mapView.pickMapItems(at: origin, radius: 2, completion: onMapItemsPicked)
}
// Completion handler to receive picked map items.
func onMapItemsPicked(pickedMapItems: PickMapItemsResult?) {
guard let topmostMapMarker = pickedMapItems?.markers.first else {
return
}
if let searchResultMetadata =
topmostMapMarker.metadata?.getCustomValue(key: "key_search_result") as? SearchResultMetadata {
let title = searchResultMetadata.searchResult.title
let vicinity = searchResultMetadata.searchResult.address.addressText
showDialog(title: "Picked Search Result",
message: "Title: \(title), Vicinity: \(vicinity)")
return
}
showDialog(title: "Map Marker picked at: ",
message: "\(topmostMapMarker.coordinates.latitude), \(topmostMapMarker.coordinates.longitude)")
}
// Conforming to LongPressDelegate protocol.
func onLongPress(state: GestureState, origin: Point2D) {
if (state == .begin) {
let geoCoordinates = mapView.viewToGeoCoordinates(viewCoordinates: origin)
addPoiMapMarker(geoCoordinates: geoCoordinates!)
getAddressForCoordinates(geoCoordinates: geoCoordinates!)
}
}
private func getAddressForCoordinates(geoCoordinates: GeoCoordinates) {
// By default results are localized in EN_US.
let reverseGeocodingOptions = SearchOptions(languageCode: LanguageCode.enGb,
maxItems: 1)
_ = searchEngine.search(coordinates: geoCoordinates,
options: reverseGeocodingOptions,
completion: onReverseGeocodingCompleted)
}
// Completion handler to receive reverse geocoding results.
func onReverseGeocodingCompleted(error: SearchError?, items: [Place]?) {
if let searchError = error {
showDialog(title: "ReverseGeocodingError", message: "Error: \(searchError)")
return
}
// If error is nil, it is guaranteed that the place list will not be empty.
let addressText = items!.first!.address.addressText
showDialog(title: "Reverse geocoded address:", message: addressText)
}
private func addPoiMapMarker(geoCoordinates: GeoCoordinates) {
let mapMarker = createPoiMapMarker(geoCoordinates: geoCoordinates)
mapView.mapScene.addMapMarker(mapMarker)
mapMarkers.append(mapMarker)
}
private func addPoiMapMarker(geoCoordinates: GeoCoordinates, metadata: Metadata) {
let mapMarker = createPoiMapMarker(geoCoordinates: geoCoordinates)
mapMarker.metadata = metadata
mapView.mapScene.addMapMarker(mapMarker)
mapMarkers.append(mapMarker)
}
private func createPoiMapMarker(geoCoordinates: GeoCoordinates) -> MapMarker {
guard
let image = UIImage(named: "poi"),
let imageData = image.pngData() else {
fatalError("Error: Image not found.")
}
let mapMarker = MapMarker(at: geoCoordinates,
image: MapImage(pixelData: imageData,
imageFormat: ImageFormat.png),
anchor: Anchor2D(horizontal: 0.5, vertical: 1))
return mapMarker
}
private func getMapViewCenter() -> GeoCoordinates {
let scaleFactor = UIScreen.main.scale
let mapViewWidthInPixels = Double(mapView.bounds.width * scaleFactor)
let mapViewHeightInPixels = Double(mapView.bounds.height * scaleFactor)
let centerPoint2D = Point2D(x: mapViewWidthInPixels / 2,
y: mapViewHeightInPixels / 2)
return mapView.viewToGeoCoordinates(viewCoordinates: centerPoint2D)!
}
private func getMapViewGeoBox() -> GeoBox {
let scaleFactor = UIScreen.main.scale
let mapViewWidthInPixels = Double(mapView.bounds.width * scaleFactor)
let mapViewHeightInPixels = Double(mapView.bounds.height * scaleFactor)
let bottomLeftPoint2D = Point2D(x: 0, y: mapViewHeightInPixels)
let topRightPoint2D = Point2D(x: mapViewWidthInPixels, y: 0)
let southWestCorner = mapView.viewToGeoCoordinates(viewCoordinates: bottomLeftPoint2D)!
let northEastCorner = mapView.viewToGeoCoordinates(viewCoordinates: topRightPoint2D)!
// Note: This algorithm assumes an unrotated map view.
return GeoBox(southWestCorner: southWestCorner, northEastCorner: northEastCorner)
}
private func showDialog(title: String, message: String) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
viewController.present(alertController, animated: true, completion: nil)
}
private func clearMap() {
for mapMarker in mapMarkers {
mapView.mapScene.removeMapMarker(mapMarker)
}
mapMarkers.removeAll()
}
}