-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpromisifyingGeoLocationAPI.js
More file actions
173 lines (152 loc) · 5.87 KB
/
Copy pathpromisifyingGeoLocationAPI.js
File metadata and controls
173 lines (152 loc) · 5.87 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
"use strict";
const btn = document.querySelector(".btn-country");
const countriesContainer = document.querySelector(".countries");
// ? Navigator:
// ! Navigator is an Object that represents the web browser
// “Actually it is just an object that acts as an interface.”
// Object instance created by the browser that acts as that interface — implemented via prototype-based inheritance.
// Type : Property of the global window object
//! Purpose : Provides info & access to device/browser features
// Examples: navigator.geolocation, navigator.clipboard, navigator.onLine, etc.
// ? GeoLocation API:
//! The navigator.geolocation API in JavaScript allows web applications to get the user's current geographic location — like latitude, longitude, and sometimes even altitude or speed — using the device’s GPS, Wi-Fi, or IP address.
// navigator.geolocation
// ? getCurrentPosition()
// ! A method that asks the browser to get the user’s current geographic location once (latitude, longitude, etc.)..
// ? Arguments:
// successCallback : Called when location is successfully obtained
// errorCallback : Called if there’s an error (user denied, timeout, etc.)
// options : Configuration options (like accuracy, timeout, cache)
navigator.geolocation.getCurrentPosition(
(position) => {
console.log(position.coords);
const { latitude, longitude } = position.coords;
console.log(latitude, longitude);
// So this is how we get the users current location coordinates
},
(err) => console.log(err)
);
// ! Now GeoLocation is purely a callback based API and lets make it a promise based API
// render Country
const renderCountry = function (data, className = "") {
let lang = Object.values(data.languages);
lang = lang.length > 1 ? lang[1] : lang[0];
const html = `
<article class="country ${className}">
<img class="country__img" src=${data.flags.png} />
<div class="country__data">
<h3 class="country__name">${data.name.common}</h3>
<h4 class="country__region">${data.region}</h4>
<p class="country__row"><span>👫</span>${(
data.population / 1000000
).toFixed(1)}</p>
<p class="country__row"><span>🗣️</span>${lang}</p>
<p class="country__row"><span>💰</span>${
Object.values(data.currencies)[0].name
}</p>
</div>
</article>
`;
countriesContainer.insertAdjacentHTML("beforeend", html);
};
// get country based on coordinates: the old version
// const whereAmI = function (lat, lng) {
// if (typeof lat !== "number" || typeof lng !== "number") {
// console.log("Coordinates are in incorrect form");
// return;
// }
// fetch(
// `https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=${lat}&lon=${lng}`
// )
// .then((response) => {
// // console.log(response);
// if (!response.ok)
// throw new Error(
// "No location Found, Coordinates doesn't exists or Incorrect!"
// );
// return response.json();
// })
// .then((data) => {
// // console.log(data);
// // console.log(data.address);
// const { address } = data;
// // console.log(address);
// console.log(`You are in ${address.city} ${address.country}`);
// return fetch(`https://restcountries.com/v3.1/name/${address.country}`);
// })
// .then((response) => {
// if (!response.ok)
// throw new Error(`Country not found. Error: ${response.status} `);
// return response.json();
// })
// .then((data) => {
// // console.log(data[0]);
// renderCountry(data[0]);
// })
// .catch((err) => {
// // console.log("test");
// console.error(err.message);
// })
// .finally(() => {
// // console.log("from finally");
// countriesContainer.style.opacity = 1;
// });
// };
// To make the geolocation API promise based we will make a new promise by ourselves and return it from the function
// const getPosition = function () {
// return new Promise(function (resolve, reject) {
// navigator.geolocation.getCurrentPosition(
// (position) => resolve(position),
// (err) => reject(err)
// );
// });
// };
// we can do exact same function in this fashion: it is just the same thing as implemented above
const getPosition = function () {
return new Promise(function (resolve, reject) {
navigator.geolocation.getCurrentPosition(resolve, reject);
});
};
// now as we know getPosition() will return a promise and to handle that we have to use the then()
getPosition()
.then((res) => console.log(res.coords))
.catch((err) => console.log(err));
// So we just promisified the GeoLocationAPI
//! we can make a function to render our location based on the coordinates given by the browser
const whereAmI = function () {
getPosition()
.then((pos) => {
const { latitude: lat, longitude: lng } = pos.coords;
return fetch(
`https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=${lat}&lon=${lng}`
);
})
.then((response) => {
if (!response.ok)
throw new Error(
"No location Found, Coordinates doesn't exists or Incorrect!"
);
return response.json();
})
.then((data) => {
const { address } = data;
console.log(`You are in ${address.city} ${address.country}`);
return fetch(`https://restcountries.com/v3.1/name/${address.country}`);
})
.then((response) => {
if (!response.ok)
throw new Error(`Country not found. Error: ${response.status} `);
return response.json();
})
.then((data) => {
renderCountry(data[0]);
})
.catch((err) => {
console.error(err.message);
})
.finally(() => {
countriesContainer.style.opacity = 1;
});
};
btn.addEventListener("click", whereAmI);
// This is how we can promisify any callback based process