You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
description: Learn how to build a cafe finder with JavaScript
7
7
header: https://i.imgur.com/VKm4oPJ.gif
8
-
bannerImage: https://i.imgur.com/VKm4oPJ.gif
8
+
bannerImage: https://i.imgur.com/lfbCFid.gif
9
9
published: live
10
10
tags:
11
11
- intermediate
12
12
- javascript
13
13
---
14
14
15
15
<BannerImage
16
-
link="https://i.imgur.com/VKm4oPJ.gif"
16
+
link="https://i.imgur.com/lfbCFid.gif"
17
17
description=""
18
18
uid={false}
19
19
cl="for-sidebar"
@@ -29,38 +29,37 @@ tags:
29
29
/>
30
30
31
31
<BannerImage
32
-
link="https://i.imgur.com/VKm4oPJ.gif"
32
+
link="https://i.imgur.com/lfbCFid.gif"
33
33
description=""
34
34
uid="CgUQBagDrWWBRUuoh3mkyi3aedg1"
35
35
/>
36
36
37
-
**Prerequisites: HTML, CSS, JavaScript**
38
-
37
+
**Prerequisites:** HTML, CSS, JavaScript
39
38
**Read Time:** 30 minutes
40
39
41
40
## Introduction
42
41
43
-
If you're an iced-bev-meets-coworking-space fiend like me and want to shake up what cafe you head to next, this is the perfect project for you. We'll be using our trilogy of web dev tools: ****HTML****, ****CSS****, and ****JavaScript****, and an API from the Google Maps Platform called ****Places****. We'll also make some quick animations and implement swiping recognition with a JavaScript library called ****Hammer****!
42
+
If you're an iced-bev-meets-coworking-space fiend like me and want to shake up what cafe you head to next, this is the perfect project for you. We'll be using our trilogy of web dev tools: HTML, CSS, and JavaScript, and an API from the Google Maps Platform called [Places](https://developers.google.com/maps/documentation/places/web-service/overview). We'll also make some quick animations and implement swiping recognition with a JavaScript library called [Hammer](https://hammerjs.github.io)!
44
43
45
44
## About the Google Maps Platform
46
45
47
-
The Google Maps Platform is a collection of Application Programming Interfaces (APIs) and Software Development Kits (SDKs). Each tool on the platform lets users use Google Maps functions and data in their own projects!
46
+
The [Google Maps Platform](https://mapsplatform.google.com) is a collection of Application Programming Interfaces (APIs) and Software Development Kits (SDKs). Each tool on the platform lets users use Google Maps functions and data in their own projects!
48
47
49
48
Some popular apps that use the Google Maps Platform include Uber and Airbnb, which access a user's location to calculate rides and show rentals in specific areas!
The [Places API](https://developers.google.com/maps/documentation/places/web-service/overview) is a smaller API under the Google Maps API. It fetches location data like location names, addresses, photos, and many more attributes! It's a great tool for accessing updated data and finding multiple places without manually copying all of their information into a project. ****We'll be using this in our project!****
52
+
The [Places API](https://developers.google.com/maps/documentation/places/web-service/overview) is a smaller API under the Google Maps API. It fetches location data like location names, addresses, photos, and many more attributes! It's a great tool for accessing updated data and finding multiple places without manually copying all of their information into a project. We'll be using this in our project!
54
53
55
54
## Setup
56
55
57
56
### Workspace
58
57
59
-
Start by creating a new HTML/CSS/JS project in [Codédex Builds](https://www.codedex.io/builds). You can also use a Code editor of your choice, like [VSCode](https://code.visualstudio.com/).
58
+
Start by creating a new HTML/CSS/JS project in [Codédex Builds](https://www.codedex.io/builds). You can also use a code editor of your choice, like [VS Code](https://code.visualstudio.com/).
60
59
61
60
### Google Cloud Console
62
61
63
-
Set up your project in the [[Google Cloud Console](https://developers.google.com/maps/documentation/elevation/cloud-setup). You'll enter a project name and billing information. Your website won't work as it should unless you enable billing, but you won't be charged if the API doesn't get called past the monthly limit (we'll teach you how to cap it at the limit, which is usually 10,000 API calls).
62
+
Set up your project in the [Google Cloud Console](https://developers.google.com/maps/documentation/elevation/cloud-setup). You'll enter a project name and billing information. Your website won't work as it should unless you enable billing, but you won't be charged if the API doesn't get called past the monthly limit (we'll teach you how to cap it at the limit, which is usually 10,000 API calls).
64
63
65
64
### Clone Template
66
65
@@ -87,67 +86,62 @@ Here's how to create and protect your API key:
87
86
3. Make sure you're on your cafe finder project and select the APIs & Services button.
88
87
4. On the left menu, click on library.
89
88
5. Search for the Places API (new) and click on it. Make sure the Places API is enabled.
90
-
6. Click on the hamburger menu and look for the APIs & Services button again. Then click on ****create****credentials****, then API key.
89
+
6. Click on the hamburger menu and look for the APIs & Services button again. Then click on **createcredentials**, then API key.
91
90
7. After your key is generated, click on edit key. Restrict your application to websites.
92
-
8. Add the domain your project is hosted on. In my case, mine is hosted on Codédex builds.
91
+
8. Add the domain your project is hosted on. In my case, mine is hosted on Codédex Builds.
93
92
94
93
Put your API key at the top of your JavaScript file. It should look like this:
95
94
96
95
```jsx
97
96
constapiKey="STRING_OF_RANDOM_CHARACTERS_HERE";
98
97
```
99
98
100
-
<aside>
101
-
⚠️
102
-
103
-
****Make sure your API key is restricted to just your project (step 7), or else anyone can use it freely and you'll get charged for it!****
104
-
105
-
</aside>
99
+
**⚠️ Warning:** Make sure your API key is restricted to just your project (step 7), or else anyone can use it freely and you'll get charged for it!
106
100
107
101
### cors-anywhere
108
102
109
-
Head to [https://cors-anywhere.herokuapp.com/](https://cors-anywhere.herokuapp.com/). Make sure to click on the ``Request temporary access to the demo server`` button to get set up with a temporary server for your project.
103
+
Head to [https://cors-anywhere.herokuapp.com](https://cors-anywhere.herokuapp.com/). Make sure to click on the ``Request temporary access to the demo server`` button to get set up with a temporary server for your project.
110
104
111
105
Then, add these lines to the top of your JavaScript file.
To see cafes nearby, the browser needs access to your location. There's a built-in JavaScript function that takes care of that for you called ``useLocation()`` and it takes your device's latitude and longitude coordinates.
Next, we'll check if any location data has been cached (saved to the browser) and is less than 10 minutes old.
129
123
130
124
```jsx
131
125
if (cache.timestamp&& now -cache.timestamp<10*60*1000) {
132
-
useLocation(cache.lat, cache.lng);
133
-
}
126
+
useLocation(cache.lat, cache.lng);
127
+
}
134
128
```
135
129
136
130
If there's no cached location information found, the browser pulls your current latitude and longitude from a built-in function.
137
131
138
132
```jsx
139
133
else {
140
-
navigator.geolocation.getCurrentPosition(pos=> {
141
-
constlat=pos.coords.latitude;
142
-
constlng=pos.coords.longitude;
134
+
navigator.geolocation.getCurrentPosition(pos=> {
135
+
constlat=pos.coords.latitude;
136
+
constlng=pos.coords.longitude;
143
137
```
144
138
145
-
We'll save the location and timestamp in ``localStorage`` in case we use our cafe finder website in the near future. Then we'll add error handling - an alert that lets you know if your location can't be accessed.
139
+
We'll save the location and timestamp in `localStorage` in case we use our cafe finder website in the near future. Then we'll add error handling - an alert that lets you know if your location can't be accessed.
146
140
147
141
```jsx
148
-
localStorage.setItem('cachedLocation', JSON.stringify({ lat, lng, timestamp: now }));
149
-
useLocation(lat, lng);
150
-
}, () =>alert("Location access denied or unavailable."));
142
+
localStorage.setItem('cachedLocation', JSON.stringify({ lat, lng, timestamp: now }));
143
+
useLocation(lat, lng);
144
+
}, () =>alert("Location access denied or unavailable."));
151
145
```
152
146
153
147
### Using the API
@@ -166,8 +160,8 @@ We'll call the API to find nearby cafes and *_fetch_* their urls.
166
160
167
161
```jsx
168
162
try {
169
-
constresponse=awaitfetch(url);
170
-
constdata=awaitresponse.json();
163
+
constresponse=awaitfetch(url);
164
+
constdata=awaitresponse.json();
171
165
```
172
166
173
167
If the API finds results for nearby cafes, we'll take that data and insert it into cards (we'll write the `displayCards` function next!)
@@ -193,26 +187,26 @@ We'll start by creating a container that takes the first saved cafe in our cafe
193
187
194
188
```jsx
195
189
functiondisplayCards(cafes) {
196
-
constcontainer=document.querySelector('.cards');
197
-
container.innerHTML='';
190
+
constcontainer=document.querySelector('.cards');
191
+
container.innerHTML='';
198
192
```
199
193
200
194
We'll then make a for loop that iterates through the cafe list to…
201
195
202
196
- Create a new div to wrap each cafe card
203
-
- Add a class (``swipe-wrapper``) to each card to keep card styles consistent
204
-
- Adjust the card's ****z-index**** (display order) so that new cards appear under old ones
197
+
- Add a class (`swipe-wrapper`) to each card to keep card styles consistent
198
+
- Adjust the card's **z-index** (display order) so that new cards appear under old ones
205
199
206
200
```jsx
207
-
cafes.forEach((cafe, i) => {
208
-
constwrapper=document.createElement('div');
209
-
wrapper.className='swipe-wrapper';
210
-
wrapper.style.zIndex=200- i;
211
-
212
-
var newCards =document.querySelectorAll('.location-card:not(.removed)');
213
-
var allCards =document.querySelectorAll('.location-card');
214
-
});
215
-
}
201
+
cafes.forEach((cafe, i) => {
202
+
constwrapper=document.createElement('div');
203
+
wrapper.className='swipe-wrapper';
204
+
wrapper.style.zIndex=200- i;
205
+
206
+
var newCards =document.querySelectorAll('.location-card:not(.removed)');
207
+
var allCards =document.querySelectorAll('.location-card');
208
+
});
209
+
}
216
210
```
217
211
218
212
We'll add more inside the function that inserts location information into each card by calling the Places API. Add a line that creates a card div and another line that assigns the card's class name to be ``location-card``.
@@ -239,7 +233,7 @@ const cafeData = {
239
233
};
240
234
```
241
235
242
-
Putting in tags between the ````` symbol when changing an element's ``innerHTML`` allows you to render HTML elements when functions run. We'll append (connect) the card to its wrapper, and append its wrapper to its container.
236
+
Putting in tags between the `````` symbol when changing an element's `innerHTML` allows you to render HTML elements when functions run. We'll append (connect) the card to its wrapper, and append its wrapper to its container.
[Hammer](http://hammerjs.github.io/) is a library used to recognize touch gestures in the browser!
259
253
260
-
<aside>
261
-
💡
262
-
263
-
A**library** is a collection of reusable resources like functions, classes, and pieces of pre-written code. An**API** is an interface that lets your code communicate with another application.
264
-
265
-
</aside>
254
+
💡 A **library** is a collection of reusable resources like functions, classes, and pieces of pre-written code. An **API** is an interface that lets your code communicate with another application.
266
255
267
256
To make sure we have swiping gestures detected on the site, we're gonna import the library by adding this line in the ``<head>`` of your HTML file:
268
257
@@ -274,17 +263,17 @@ We're going to add a function that detects left and right swipes and makes each
We'll need a fallback in case the cafe is already saved. Write an `else` statement that alerts the user if a cafe has already been saved, so it doesn't get duplicated into the saved list of cafes.
315
304
316
305
```jsx
317
-
else {
306
+
else {
318
307
alert(`${cafe.name} is already saved.`);
319
308
}
320
309
}
@@ -328,8 +317,8 @@ Start by writing a function called `showSaved()`. Similar to the `displayCards()
328
317
329
318
```jsx
330
319
functionshowSaved() {
331
-
constcontainer=document.querySelector('.cards');
332
-
container.innerHTML='';
320
+
constcontainer=document.querySelector('.cards');
321
+
container.innerHTML='';
333
322
```
334
323
335
324
Then, add this line to parse through the list of saved cafes and save the information in a variable.
@@ -342,9 +331,9 @@ If the saved array is empty, it'll update the page by adding a ``<p>`` tag to sa
For each cafe in the saved array, we'll make a card div, add the `location-card` class name, and update the card's content with `innerHTML` to include the current cafe's information.
@@ -383,7 +372,7 @@ If you're looking for another challenge or a way to spice up your project, you c
383
372
384
373
### Troubleshooting
385
374
386
-
- Make sure you're granted temporary access on https://cors-anywhere.herokuapp.com/.
375
+
- Make sure you're granted temporary access on https://cors-anywhere.herokuapp.com.
387
376
- Make sure to allow location access when you try out the site.
0 commit comments