-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
89 lines (70 loc) · 2.5 KB
/
app.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
const key = 'at_1mdHJlTD3nld8r3lcRAQx3niVEfyH';
const apiUrl = 'https://geo.ipify.org/api/';
const ipify = 'https://api.ipify.org?format=json';
// Card elements to be updated
let card = document.querySelector('.card');
let address = document.querySelector('.first');
let city = document.querySelector('.second');
let timeZone = document.querySelector('.third');
let isp = document.querySelector('.fourth');
let map
//form elements
const input = document.querySelector('input');
const form = document.querySelector('#form');
//here i get the users ip address on loading the window
window.addEventListener('load',()=>{
// I fetch my Ipify Url for generating user Ip
fetch(ipify)
.then(resp=> {
if(!resp.ok) {
// throw an error if the user IP couldn't be fetched
throw Error('Error while fetching your IP');
} else{
// if everything goes well
return resp.json();
}
})
// here i log the ip address fetched to the user input
.then(data=>{
fetchIpDetails(data.ip);
})
.catch(err => console.log(err));
})
// here i created the function to search and then get your IP details logged
form.addEventListener('submit', (e)=>{
map.remove();
e.preventDefault();
fetchIpDetails(input.value);
input.value = '';
})
// here i created the function to render my map using leaflet and cloud maptiler
const renderMap = (lat,lng)=>{
map = L.map('map', {
center: [lat,lng],
zoom: 6
},
);
L.tileLayer('https://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',{
license: 'Map data ©<a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
subdomains:['mt0','mt1','mt2','mt3'],
maxZoom: 25,
enableHighAccuracy: true,
}).addTo(map);
L.marker([lat,lng]).addTo(map);
}
//here i fetch the ip details of the user
const fetchIpDetails = (e)=>{
fetch(`https://geo.ipify.org/api/v2/country,city?apiKey=at_1mdHJlTD3nld8r3lcRAQx3niVEfyH&ipAddress=${e}`)
.then(resp=> resp.json())
.then(data =>{
renderMap(data.location?.lat,data.location?.lng);
renderDetails(data);
});
}
//here i render my card details
const renderDetails =(details)=>{
address.innerHTML = details.ip;
city.innerHTML = `${details.location.city}, ${details.location.region}, ${details.location.postalCode}`;
timeZone.innerHTML = details.location.timezone;
isp.innerHTML= details.isp;
}