This repository has been archived by the owner on Feb 14, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathPhotonAddressEngine.js
101 lines (86 loc) · 2.73 KB
/
PhotonAddressEngine.js
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
import Bloodhound from 'corejs-typeahead/dist/bloodhound';
import Options from './Options';
export default class PhotonAddressEngine extends Bloodhound {
options;
jQuery;
constructor(options, $ = window.$) {
options = new Options(options);
super({
local: [],
queryTokenizer: Bloodhound.tokenizers.nonword,
datumTokenizer: PhotonAddressEngine.datumTokenizer,
identify: PhotonAddressEngine.identify,
remote: {
url: options.api,
sufficient: options.limit,
prepare: (query, settings) => {
settings.data = options.reqParams;
settings.data.q = query;
return settings;
},
transform: (response) => {
response.features.forEach((feature) => {
feature.description = options.formatResultFunc(feature);
});
return response.features || [];
}
}
});
this.options = options;
this.jQuery = $;
}
search(query, sync, async) {
const syncPromise = this.jQuery.Deferred();
const asyncPromise = this.jQuery.Deferred();
super.search(query, (datums) => {
syncPromise.resolve(datums);
}, (datums) => {
asyncPromise.resolve(datums);
});
this.jQuery.when(syncPromise, asyncPromise)
.then((syncResults, asyncResults) => {
const allResults = [].concat(syncResults, asyncResults);
this.jQuery(this).trigger('addresspicker:predictions', [ allResults ]);
sync(syncResults);
async(asyncResults);
});
}
/**
* Transforms default typeahead event 'typeahead:selected' to
* 'addresspicker:selected'. The same event is triggered by
* bloodhound.reverseGeocode.
*
* @param typeahead jquery wrapper around address input
*/
bindDefaultTypeaheadEvent(typeahead) {
typeahead.bind('typeahead:selected', (event, place) => {
this.jQuery(this).trigger('addresspicker:selected', [ place ]);
});
}
/**
* Makes reverse geocoding of position and triggers event
* 'addresspicker:selected' with result.
*
* @param position array with latitude & longitude
*/
reverseGeocode(position) {
this.jQuery.get(this.options.reverse, {
lat: position[0],
lon: position[1]
}).then((response) => {
if (response.features) {
const firstFeature = response.features[0];
firstFeature.description = this.options.formatResultFunc(firstFeature);
this.jQuery(this).trigger('addresspicker:selected', [ firstFeature ]);
}
});
}
static datumTokenizer(feature) {
return Bloodhound.tokenizers.obj.whitespace([
'country', 'city', 'postcode', 'name', 'state'
])(feature.properties);
}
static identify(feature) {
return feature.properties.osm_id;
}
}