forked from Yoko-Co/yoko-algolia-custom-map-test
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
206 lines (180 loc) · 5.4 KB
/
script.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
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
function init( appId, apiKey, index) {
// Get Algolia App ID from env
const ALGOLIA_APP_ID = appId;
// Get Aloglia API Key from env
const ALGOLIA_API_KEY = apiKey;
// Get Algolia Index from env
const ALGOLIA_INDEX = index;
// Initialize InstantSearch
const search = instantsearch({
indexName: ALGOLIA_INDEX,
searchClient: algoliasearch(ALGOLIA_APP_ID, ALGOLIA_API_KEY),
});
// Add search box
search.addWidgets([
instantsearch.widgets.searchBox({
container: '#searchbox',
placeholder: 'Search for Engineers',
}),
]);
// Add hits widget
search.addWidgets([
instantsearch.widgets.hits({
container: '#hits',
templates: {
item: `
<h3 class="hit-name">{{#helpers.highlight}}{ "attribute": "name" }{{/helpers.highlight}}</h3>
<p class="hit-role">{{#helpers.highlight}}{ "attribute": "role" }{{/helpers.highlight}}</p>
`,
},
}),
]);
// Add geoSearch connector
const { connectGeoSearch } = instantsearch.connectors;
// Create the render function
let map = null;
let markers = [];
let isUserInteraction = true;
const renderGeoSearch = (renderOptions, isFirstRendering) => {
const {
items,
position,
currentRefinement,
refine,
sendEvent,
clearMapRefinement,
isRefinedWithMap,
toggleRefineOnMapMove,
isRefineOnMapMove,
setMapMoveSinceLastRefine,
hasMapMoveSinceLastRefine,
widgetParams
} = renderOptions;
const {
container,
googleReference,
initialZoom,
initialPosition,
mapOptions,
builtInMarker,
customHTMLMarker,
enableRefine,
enableClearMapRefinement,
enableRefineControl,
enableRefineOnMapMove,
templates,
cssClasses
} = widgetParams;
if (isFirstRendering) {
// initialize map with Leaflet
map = L.map(container);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution:
'© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors',
}).addTo(map);
// read refine on move setting if provided
if (enableRefineOnMapMove && enableRefineOnMapMove !== isRefineOnMapMove()) {
// if the provided setting and the current setting don't match, toggle it
toggleRefineOnMapMove();
}
// refine result set on movement event handler
// TODO: consider adding and removing this event when refine on move is toggled
map.on('moveend', () => {
if (isUserInteraction && isRefineOnMapMove()) {
const ne = map.getBounds().getNorthEast();
const sw = map.getBounds().getSouthWest();
refine({
northEast: { lat: ne.lat, lng: ne.lng },
southWest: { lat: sw.lat, lng: sw.lng },
});
}
});
// toggle for refinement on move if allowed
// check if not false - default is true and it may not be explicitly passed in
if (enableRefineControl != false) {
const refineControl = document.querySelector('#refine-on-move');
refineControl.checked = isRefineOnMapMove() ? 'checked' : '';
refineControl.addEventListener('change', function(event) {
toggleRefineOnMapMove();
});
document.querySelector('#refine-control').style.display = 'block'; // show toggle control
}
// reset map button if resetting refinement is allowed
// check if not false - default is true and it may not be explicitly passed in
if (enableClearMapRefinement != false) {
const resetButton = document.createElement('button');
resetButton.className = 'map-control map-btn--reset';
resetButton.textContent = 'Reset Map';
resetButton.addEventListener('click', () => {
clearMapRefinement();
});
container.appendChild(resetButton);
}
}
document.querySelector('button').hidden = !currentRefinement;
markers.forEach(marker => marker.remove());
markers = items.map(({ name, role, _geoloc }) => {
let marker = L.marker([_geoloc.lat, _geoloc.lng]);
let tooltip = L.tooltip();
tooltip.setContent(`<p class="map-marker-name">${name}<p><p class="map-marker-role">${role}</p>`);
marker.bindTooltip(tooltip).openTooltip();
marker.addTo(map);
return marker;
});
isUserInteraction = false;
if (!currentRefinement && markers.length) {
map.fitBounds(L.featureGroup(markers).getBounds(), {
animate: false,
});
} else if (!currentRefinement) {
map.setView(initialPosition, initialZoom, {
animate: false,
});
}
isUserInteraction = true;
};
// 2. Create the custom widget
const customGeoSearch = connectGeoSearch(
renderGeoSearch
);
// 3. Instantiate
search.addWidgets([
customGeoSearch(
{
container: document.querySelector('#map'),
initialPosition: {
lat: 13.493493107850682,
lng: -89.38474698770433
},
initialZoom: 13,
transformItems(items) {
const newItems = [];
for (let i = 0; i < items.length; i++) {
const engineer = items[i];
for(let l = 0; l < engineer._geoloc.length; l++) {
newItems.push({name: engineer.name, role: engineer.role, objectID: engineer.objectID, _geoloc: {
lat: engineer._geoloc[l].lat,
lng: engineer._geoloc[l].lng,
}});
}
}
return newItems;
}
}
)
]);
search.start();
};
// On Document Ready with Vanilla JS
document.addEventListener('DOMContentLoaded', function() {
try {
// Get variables from env.
const appId = ALGOLIA_APP_ID;
const apiKey = ALGOLIA_API_KEY;
const index = ALGOLIA_INDEX;
// Initialize InstantSearch
init(appId, apiKey, index);
} catch (error) {
console.error('Error:', error);
}
});