-
Notifications
You must be signed in to change notification settings - Fork 395
Expand file tree
/
Copy pathMapboxSearchProvider.ts
More file actions
279 lines (249 loc) · 8.29 KB
/
MapboxSearchProvider.ts
File metadata and controls
279 lines (249 loc) · 8.29 KB
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
import { Feature, Point } from "geojson";
import i18next from "i18next";
import { makeObservable, override, runInAction } from "mobx";
import Rectangle from "terriajs-cesium/Source/Core/Rectangle";
import Resource from "terriajs-cesium/Source/Core/Resource";
import {
Category,
SearchAction
} from "../../Core/AnalyticEvents/analyticEvents";
import isDefined from "../../Core/isDefined";
import loadJson from "../../Core/loadJson";
import { applyTranslationIfExists } from "../../Language/languageHelpers";
import prettifyCoordinates from "../../Map/Vector/prettifyCoordinates";
import LocationSearchProviderMixin, {
getMapCenter
} from "../../ModelMixins/SearchProviders/LocationSearchProviderMixin";
import MapboxSearchProviderTraits from "../../Traits/SearchProviders/MapboxSearchProviderTraits";
import CommonStrata from "../Definition/CommonStrata";
import CreateModel from "../Definition/CreateModel";
import Terria from "../Terria";
import SearchProviderResult from "./SearchProviderResults";
import SearchResult from "./SearchResult";
enum MapboxGeocodeDirection {
Forward = "forward",
Reverse = "reverse"
}
interface MapboxGeocodingResponse {
features: Feature<Point>[];
type: string;
attribution?: string;
}
export default class MapboxSearchProvider extends LocationSearchProviderMixin(
CreateModel(MapboxSearchProviderTraits)
) {
static readonly type = "mapbox-search-provider";
get type() {
return MapboxSearchProvider.type;
}
constructor(uniqueId: string | undefined, terria: Terria) {
super(uniqueId, terria);
makeObservable(this);
}
@override
override showWarning() {
if (!this.accessToken || this.accessToken === "") {
console.warn(
`The ${applyTranslationIfExists(this.name, i18next)}(${
this.type
}) geocoder will always return no results because a Mapbox token has not been provided. Please get a token from mapbox.com and add it to parameters.mapboxSearchProviderAccessToken in config.json.`
);
}
}
protected logEvent(searchText: string) {
this.terria.analytics?.logEvent(
Category.search,
SearchAction.mapbox,
searchText
);
}
protected doSearch(
searchText: string,
searchResults: SearchProviderResult
): Promise<void> {
searchResults.results.length = 0;
searchResults.message = undefined;
const isCoordinate = RegExp(
/^-?([0-9]{1,2}|1[0-7][0-9]|180)(\.[0-9]{1,17})$/
);
const isCSCoordinatePair = RegExp(
/([+-]?\d+\.?\d+)\s*,\s*([+-]?\d+\.?\d+)/
);
let searchDirection = isCSCoordinatePair.test(searchText)
? MapboxGeocodeDirection.Reverse
: MapboxGeocodeDirection.Forward;
let queryParams = {
access_token: this.accessToken,
autocomplete: this.partialMatch,
language: this.language
};
//check if geocoder should be reverse and set up.
if (searchDirection === MapboxGeocodeDirection.Reverse) {
let lonLat = searchText.split(/\s+/).join("").split(",");
if (
lonLat.length === 2 &&
isCoordinate.test(lonLat[0]) &&
isCoordinate.test(lonLat[1])
) {
// need to reverse the coord order if true.
if (this.latLonSearchOrder) {
lonLat = lonLat.reverse();
}
const [lonf, latf] = lonLat.map(parseFloat);
if (this.showCoordinatesInReverseGeocodeResult) {
const prettyCoords = prettifyCoordinates(lonf, latf);
searchResults.results.push(
new SearchResult({
name: `${prettyCoords.latitude}, ${prettyCoords.longitude}`,
clickAction: createZoomToFunction(this, {
geometry: {
coordinates: [lonf, latf]
},
properties: {}
}),
location: {
longitude: lonf,
latitude: latf
}
})
);
}
queryParams = {
...queryParams,
...{
longitude: lonLat[0],
latitude: lonLat[1],
limit: 1 //limit for reverse geocoder is per type
}
};
} else {
//if lonLat fails to parse, then assume is forward geocode
searchDirection = MapboxGeocodeDirection.Forward;
}
}
const searchQuery = new Resource({
url: new URL(searchDirection, this.url).toString(),
queryParameters: queryParams
});
if (searchDirection === MapboxGeocodeDirection.Forward) {
searchQuery.appendQueryParameters({
q: searchText,
limit: this.limit
});
}
if (searchDirection === MapboxGeocodeDirection.Forward && this.mapCenter) {
const mapCenter = getMapCenter(this.terria);
searchQuery.appendQueryParameters({
proximity: `${mapCenter.longitude}, ${mapCenter.latitude}`
});
}
if (
searchDirection === MapboxGeocodeDirection.Forward &&
this.terria.searchBarModel.boundingBoxLimit
) {
const bbox = this.terria.searchBarModel.boundingBoxLimit;
if (
isDefined(bbox.west) &&
isDefined(bbox.north) &&
isDefined(bbox.east) &&
isDefined(bbox.south)
) {
searchQuery.appendQueryParameters({
bbox: [bbox.west, bbox.north, bbox.east, bbox.south].join(",")
});
}
}
if (this.country) {
searchQuery.appendQueryParameters({
country: this.country
});
}
if (this.types) {
searchQuery.appendQueryParameters({
types: this.types
});
}
if (this.worldview) {
searchQuery.appendQueryParameters({
worldview: this.worldview
});
}
const promise: Promise<any> = loadJson(searchQuery);
return promise
.then((result: MapboxGeocodingResponse) => {
if (searchResults.isCanceled) {
// A new search has superseded this one, so ignore the result.
return;
}
if (
(result.features.length === 0 &&
searchDirection === MapboxGeocodeDirection.Forward) ||
//in the case where coordinate result is true, list is
//not empty.
(result.features.length === 0 &&
searchDirection === MapboxGeocodeDirection.Reverse &&
this.showCoordinatesInReverseGeocodeResult === false)
) {
searchResults.message = {
content: "translate#viewModels.searchNoLocations"
};
return;
}
const locations: SearchResult[] = result.features
.filter(
(feat) =>
feat.properties && feat.geometry && feat.properties.full_address
)
.map((feat) => {
return new SearchResult({
name: feat.properties!.full_address,
clickAction: createZoomToFunction(this, feat),
location: {
latitude: feat.geometry.coordinates[1],
longitude: feat.geometry.coordinates[0]
}
});
});
runInAction(() => {
searchResults.results.push(...locations);
});
if (searchResults.results.length === 0) {
searchResults.message = {
content: "translate#viewModels.searchNoLocations"
};
}
const attribution = result.attribution;
if (attribution) {
runInAction(() => {
this.setTrait(CommonStrata.underride, "attributions", [
attribution
]);
});
}
})
.catch(() => {
if (searchResults.isCanceled) {
// A new search has superseded this one, so ignore the result.
return;
}
searchResults.message = {
content: "translate#viewModels.searchErrorOccurred"
};
});
}
}
function createZoomToFunction(model: MapboxSearchProvider, resource: any) {
// mapbox doesn't return a bbox for street names etc, so we
// need to create it ourselves.
const [west, north, east, south] = resource.properties.bbox ?? [
resource.geometry.coordinates[0] - 0.01,
resource.geometry.coordinates[1] - 0.01,
resource.geometry.coordinates[0] + 0.01,
resource.geometry.coordinates[1] + 0.01
];
const rectangle = Rectangle.fromDegrees(west, south, east, north);
return function () {
const terria = model.terria;
terria.currentViewer.zoomTo(rectangle, model.flightDurationSeconds);
};
}