-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlocation.html
More file actions
82 lines (79 loc) · 2.21 KB
/
location.html
File metadata and controls
82 lines (79 loc) · 2.21 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
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Get User Location</title>
<link rel="stylesheet" href="style.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<button>Detect your location</button>
<script src="script.js"></script>
</body>
</html>
<style>
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700&display=swap');
*{
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Poppins', sans-serif;
}
body{
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
background: linear-gradient(#252930 50%, #5372F0 50%);
}
::selection{
color: #fff;
background: #5372F0;
}
button{
border: none;
outline: none;
font-size: 50px;
color: #5372F0;
padding: 23px 44px;
border-radius: 10px;
cursor: pointer;
font-weight: 500;
background: #fff;
box-shadow: 0 0 20px 0 rgba(0,0,0,0.1);
}
</style>
<script>
const button = document.querySelector("button");
button.addEventListener("click", ()=>{
if(navigator.geolocation){
button.innerText = "Allow to detect location";
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}else{
button.innerText = "Your browser not support";
}
});
function onSuccess(position){
button.innerText = "Detecting your location...";
let {latitude, longitude} = position.coords;
fetch(`https://api.opencagedata.com/geocode/v1/json?q=${latitude}+${longitude}&key=198e97c6fee14f54b1e3749cb1288382`)
.then(response => response.json()).then(response =>{
let allDetails = response.results[0].components;
console.table(allDetails);
let {county, postcode, country} = allDetails;
button.innerText = `${county} ${postcode}, ${country}`;
}).catch(()=>{
button.innerText = "Something went wrong";
});
}
function onError(error){
if(error.code == 1){
button.innerText = "You denied the request";
}else if(error.code == 2){
button.innerText = "Location is unavailable";
}else{
button.innerText = "Something went wrong";
}
button.setAttribute("disabled", "true");
}
</script>