-
Notifications
You must be signed in to change notification settings - Fork 3
/
script.js
408 lines (341 loc) · 17.1 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
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
// ---------------------------------------
// << Function to build the geocode query URL >>
//
function buildGeoCodeQueryURL() {
var queryURL = "https://api.opencagedata.com/geocode/v1/json?"
var queryParameters = { "key": "7b5d7173bf8d49dbb2bd074694d9d501" }
// Getting an address input by the user
queryParameters.q = $("#addressInput").val().trim()
queryParameters.no_annotations = 1;
// Returning the queryURL for the geocoding() function
return (queryURL + $.param(queryParameters))
}
// ---------------------------------------
// << Function making an AJAX call OpenCageData >>
//
function geocoding() {
var queryURLgeocoding = buildGeoCodeQueryURL();
// Putting a return in front of the AJAX call
// To return the results of the AJAX call as the return of the function geocoding()
// Returning the coordinates of Latitude and Longitude, based on the user input search
return ($.ajax({
url: queryURLgeocoding,
method: "GET"
}).then(function(geocodeData) {
var latitude = geocodeData.results[0].geometry.lat;
var longitude = geocodeData.results[0].geometry.lng;
var coordinates = [latitude, longitude];
return coordinates;
}))
}
// ---------------------------------------
// << Function to build the Four Square query URL >>
//
async function buildFourSquareQueryURL() {
// Initializing an empty array to story the coordinates
var coordinates = [];
// Looking up the data attribute of the element with the ID of "eitherORSearch"
var eitherORsearch = document.getElementById("eitherORsearch");
var searchTYPE = eitherORsearch.getAttribute("data-searchTYPE");
// Run a series of if statements, based on the data attribute
// If an addressSearch was performed, run the geocoding function and get those coordinates
if (searchTYPE === "AddressSearch") {
// Awaiting the return from geocoding() prior to continuing the rest of the buildFourSquareQueryURL function
var coordinatesGeocoding = await geocoding();
// Use the coordinatesGeocoding as the coordinates within the buildFourSquareQueryURL function
coordinates = coordinatesGeocoding;
}
// If a search was performed based on currentLocation...
if (searchTYPE === "currentLocationSearch") {
// If the currentLocationCoordinates are set to [0,0], it is because...
// the user did not allow for location services
if (currentLocationCoordinates === [0, 0]) {
return;
}
// Else, use the currentLocationCoordinates as the coordinates within the buildFourSquareQueryURL function
else {
coordinates = currentLocationCoordinates;
}
}
// Getting the latitude and longitude individually from the coordinates
var latitude = coordinates[0];
var longitude = coordinates[1];
// RESTAURANT QUERY URL
var initialRestaurantQueryURL = "https://api.foursquare.com/v2/venues/explore?v=20180323&"
var restaurantParameters = { "client_id": "V3AXUCNPQO0HDURJKVY5Y3AC4IK0KYKWRQLLOBNMCTB4PWWE" };
restaurantParameters.client_secret = "YDOAOF5WZVS1HUEFENUD5PVOZ4FKMS0T32JFQWXG12DTF3AF";
restaurantParameters.ll = latitude + "," + longitude;
restaurantParameters.query = "food";
restaurantParameters.radius = "1000"; // 1000 meters, aka, 1km
restaurantParameters.limit = 10; // 10 results returned by default
restaurantParameters.sortByDistance = 1; // Boolean flag to sort the results by distance instead of relevance
var fourSquareRestaurantQueryURL = initialRestaurantQueryURL + $.param(restaurantParameters);
// PARKS QUERY URL
var initialParksQueryURL = "https://api.foursquare.com/v2/venues/search?v=20180323&"
var parksParameters = { "client_id": "V3AXUCNPQO0HDURJKVY5Y3AC4IK0KYKWRQLLOBNMCTB4PWWE" };
parksParameters.client_secret = "YDOAOF5WZVS1HUEFENUD5PVOZ4FKMS0T32JFQWXG12DTF3AF";
parksParameters.ll = latitude + "," + longitude;
parksParameters.query = "park"
parksParameters.radius = "2500" // 1000 meters, aka, 2.5 km
parksParameters.categoryId = "4bf58dd8d48988d163941735" // Category ID for PARKS
parksParameters.limit = 10; // 10 results returned by default
parksParameters.sortByDistance = 1; // Boolean flag to sort the restuls by distance instead of relevance
var fourSquareParksQueryURL = initialParksQueryURL + $.param(parksParameters);
// RETURNING BOTH QUERY URLS
var queryURLs = [fourSquareRestaurantQueryURL, fourSquareParksQueryURL];
return queryURLs;
}
// ---------------------------------------
// << Function making an AJAX call to Four Square >>
//
async function fourSquareAJAXcall(event) {
event.preventDefault();
// CLEARING the previous content from the divs
$("#restaurantsDiv").empty();
$("#parksDiv").empty();
// Awaiting the return from buildFourSquareQueryURL prior to continuing the rest of the fourSquareAJAXcall function
var queryURLs = await buildFourSquareQueryURL();
// The queryURLs to be used for the Restaurant and Parks AJAX calls
var fourSquareRestaurantQueryURL = queryURLs[0];
var fourSquareParksQueryURL = queryURLs[1];
// RESTAURANT AJAX CALL
$.ajax({
dataType: "json",
url: fourSquareRestaurantQueryURL,
data: {},
success: function(data) {
// Code for handling API response
// DETERMINING HOW MANY RESTAURANTS TO DISPLAY
// (Up to a maximum of 10)
var maximumCountRestaurants = 0
var lengthOfResponse = data.response.groups[0].items.length;
if (lengthOfResponse <= 10 && lengthOfResponse > 0) {
maximumCountRestaurants = lengthOfResponse;
} else if (lengthOfResponse === 0) {
maximumCountRestaurants = 0;
var noSearchResultsDisplay = "No search results for your area. Please try a different location.";
$("#restaurantsDiv").append(noSearchResultsDisplay);
} else {
maximumCountRestaurants = 10;
}
// Looping through the first 10 results, parsing the data, and displaying the data on the html page
for (var i = 0; i < maximumCountRestaurants; i++) {
// Getting the restaurant name
var restaurantName = data.response.groups[0].items[i].venue.name;
// Getting the restaurant address
var restaurantAddress = data.response.groups[0].items[i].venue.location.formattedAddress[0];
// Running an if / else statment to confirm if the restaurant does delivery
var doesDelivery = "";
if (data.response.groups[0].items[i].venue.delivery != undefined) {
doesDelivery = "Yes"
var devliveryProvider = data.response.groups[0].items[i].venue.delivery.provider.name;
var deliveryURL = data.response.groups[0].items[i].venue.delivery.url;
} else {
doesDelivery = "No"
}
// Getting the restaurant "genre"
var restaurantGenre = data.response.groups[0].items[i].venue.categories[0].shortName;
// Getting the icon for the restaurant "genre"
var iconPrefix = data.response.groups[0].items[i].venue.categories[0].icon.prefix;
var iconSuffix = data.response.groups[0].items[i].venue.categories[0].icon.suffix;
var imageURL = iconPrefix + "44" + iconSuffix
// BUILDING THE DIV FOR THE RESTAURANT
var individualRestaurantDiv = $("<div>");
individualRestaurantDiv.attr("class", "card")
var restHeader = $("<div>");
restHeader.attr("class", "card-header");
restHeader.attr("id", "restHeader")
restHeader.css("background", "#9EB8BD")
var restBody = $("<div>");
restBody.attr("class", "card-body")
// Creating the image for the restaurant genre icon
var image = $("<img>");
image.attr("src", imageURL);
image.css("float", "right");
// Creating content for the name, address, and genre
var name = $("<h4>").text(restaurantName);
name.css("margin", "0")
var address = $("<p>").text("Address: " + restaurantAddress);
var genre = $("<p>").text("Genre: " + restaurantGenre);
restHeader.append(name, image);
restBody.append(genre, address)
// Apending everything to the div
individualRestaurantDiv.append(restHeader, restBody);
// Running a series of if statements to confirm if the restaurant does delivery
// If the restaurant doesn't do delivery, display "No Delivery Offered"
if (doesDelivery === "No") {
var restFooter = $("<div>");
restFooter.attr("class", "card-footer");
var noDeliveryURLresponse = $("<p>").text("No Delivery Offered")
restFooter.append(noDeliveryURLresponse);
individualRestaurantDiv.append(restFooter);
}
// If the restaurant does delivery, display a link to the delivery restaurant
if (doesDelivery === "Yes") {
var restFooter = $("<div>");
restFooter.attr("class", "card-footer");
var buidlingDeliveryURL = $("<a>").attr("href", deliveryURL);
buidlingDeliveryURL.text(devliveryProvider.toUpperCase());
buidlingDeliveryURL.attr("target", "_blank");
var yesDeliveryResponse = $("<p>").text("Delivery Offered");
restFooter.append(yesDeliveryResponse, buidlingDeliveryURL);
individualRestaurantDiv.append(restFooter);
}
// APPENDING THE DIV to the HTML
$("#restaurantsDiv").append(individualRestaurantDiv);
}
},
error: function(jqXHR, textStatus, errorThrown) {
// Code for handling errors in the Restaurants AJAX call
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
// Looking up the data attribute of the element with the ID of "eitherORSearch"
var eitherORsearch = document.getElementById("eitherORsearch");
var searchTYPE = eitherORsearch.getAttribute("data-searchTYPE");
// Running if statements to determine the type of error message to display
if (searchTYPE === "AddressSearch") {
var retrySearch = $("<p>").text("Please retry address search")
$("#restaurantsDiv").append(retrySearch);
}
if (searchTYPE === "currentLocationSearch") {
var retrySearch = $("<p>").text("Please Refresh Page and Allow Location")
$("#restaurantsDiv").append(retrySearch);
}
}
})
// PARKS AJAX CALL
$.ajax({
dataType: "json",
url: fourSquareParksQueryURL,
data: {},
success: function(data) {
// Code for handling API response
// DETERMINING HOW MANY PARKS TO DISPLAY
// (Up to a maximum of 10)
var maximumCountParks = 0
var lengthOfResponse = data.response.venues.length;
if (lengthOfResponse <= 10 && lengthOfResponse > 0) {
maximumCountParks = lengthOfResponse;
} else if (lengthOfResponse === 0) {
maximumCountParks = 0;
var noSearchResultsDisplay = "No search results for your area. Please try a different location.";
$("#parksDiv").append(noSearchResultsDisplay);
} else {
maximumCountParks = 10;
}
// Looping through the first 10 results, parsing the data, and displaying the data on the html page
for (var i = 0; i < maximumCountParks; i++) {
// Getting the park name
var parkName = data.response.venues[i].name;
// Getting the park address
var parkAddress = data.response.venues[i].location.formattedAddress[0];
// Getting the icon for the park
var iconPrefix = data.response.venues[i].categories[0].icon.prefix;
var iconSuffix = data.response.venues[i].categories[0].icon.suffix;
var imageURL = iconPrefix + "44" + iconSuffix
// BUILDING THE DIV FOR THE PARKS
var individualParkDiv = $("<div>");
individualParkDiv.attr("class", "card");
parkHeader = $("<div>");
parkHeader.attr("class", "card-header");
parkHeader.css("background", "#9EB8BD");
var parkBody = $("<div>");
parkBody.attr("class", "card-body")
// Creating the image for the park icon
var image = $("<img>");
image.attr("src", imageURL);
// Creating content for the name and address
var name = $("<h4>").text(parkName);
name.css("margin", "0")
parkHeader.append(name, image);
var address = $("<p>").text("Address: " + parkAddress);
parkBody.append(address);
// Apending everything to the div
individualParkDiv.append(parkHeader, parkBody);
// APPENDING THE DIV to the HTML
$("#parksDiv").append(individualParkDiv);
}
},
error: function(jqXHR, textStatus, errorThrown) {
// Code for handling errors in the AJAX calls
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
// Looking up the data attribute of the element with the ID of "eitherORSearch"
var eitherORsearch = document.getElementById("eitherORsearch");
var searchTYPE = eitherORsearch.getAttribute("data-searchTYPE");
// Running if statements to determine the type of error message to display
if (searchTYPE === "AddressSearch") {
var retrySearch = $("<p>").text("Please retry address search")
$("#parksDiv").append(retrySearch);
}
if (searchTYPE === "currentLocationSearch") {
var retrySearch = $("<p>").text("Please Refresh Page and Allow Location")
$("#parksDiv").append(retrySearch);
}
}
});
}
// ---------------------------------------
// << Event listeners to run the fourSquareAJAXcall function! >>
//
// The submitBtn button has an event listener
$("#submitBtn").on("click", function(event) {
event.preventDefault();
// Shows results div on screen
$("#resultsDiv").show();
// Setting the data attribute of data-searchTYPE
// This gets referenced within fourSquareAJAXcall
var eitherORsearch = document.getElementById("eitherORsearch");
eitherORsearch.setAttribute("data-searchTYPE", "AddressSearch")
// Running the fourSquareAJAXcall function
fourSquareAJAXcall(event)
});
// The locationBtn button has an event listener
$("#locationBtn").on("click", function(event) {
event.preventDefault();
// Shows results div on screen
$("#resultsDiv").show();
// Setting the data attribute of data-searchTYPE
// This gets referenced within fourSquareAJAXcall
var eitherORsearch = document.getElementById("eitherORsearch");
eitherORsearch.setAttribute("data-searchTYPE", "currentLocationSearch");
// Running the fourSquareAJAXcall function
fourSquareAJAXcall(event)
});
// Button that allows user to hide and show the results divs
$("#restaurantsToggle").click(function() {
$("#restaurantsDiv").toggle();
});
$("#parksToggle").click(function() {
$("#parksDiv").toggle();
});
// ---------------------------------------
// << Function that runs immediately whent the page opens >>
// If the user allows location services, it stores currentLocationCoordinates
// If the user doesn't allow location services, they can still search by address
// Location determination based on Mozilla documentation:
// https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition
let currentLocationCoordinates = [0, 0];
function currentLocation() {
function success(pos) {
var crd = pos.coords;
console.log('Your current position is:');
console.log(`Latitude : ${crd.latitude}`);
console.log(`Longitude: ${crd.longitude}`);
console.log(`More or less ${crd.accuracy} meters.`);
currentLocationCoordinates = [crd.latitude, crd.longitude];
}
function error(err) {
console.warn(`ERROR(${err.code}): ${err.message}`)
currentLocationCoordinates = [0, 0];
}
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
navigator.geolocation.getCurrentPosition(success, error, options);
}
currentLocation()