-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
84 lines (76 loc) · 2.52 KB
/
script.js
File metadata and controls
84 lines (76 loc) · 2.52 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
console.log("tinubu");
let map;
async function getIPAPI(ip = "") {
const APIKEY = "at_B5RrrTE73J93QijRsUh74cbq3vZVX";
try {
const response = await fetch(
ip
? `https://geo.ipify.org/api/v2/country,city?apiKey=${APIKEY}&ipAddress=${ip}`
: `https://ip-api.com/json/`
);
if (!response.ok)
throw new Error(`${response.status} ${response.statusText}`);
const data = await response.json();
console.log(data);
return data;
} catch (Error) {
console.log(Error);
alert(`Error: ${Error.message}`);
}
}
async function getLocation(ip = "") {
try {
const locationData = await getIPAPI(ip);
if (!locationData) throw new Error("Failed to Load Location Data");
let lat, lon, timezone, query, isp, city;
if (locationData.status === "success") {
lat = locationData.lat;
lon = locationData.lon;
timezone = locationData.timezone;
query = locationData.query;
isp = locationData.isp;
city = locationData.city;
} else if (locationData.ip) {
const { ip, location, isp: ISP } = locationData;
query = ip;
lat = location.lat;
lon = location.lng;
timezone = location.timezone;
isp = ISP;
city = location.city;
}
const updateData = [timezone, query, isp, city];
if (!timezone && !isp) throw new Error("Private IPs"); //check for private IPs
updateCard(updateData);
if (!map) {
map = L.map("map", { zoomControl: false }).setView([lat, lon], 28);
L.tileLayer("https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png", {
attribution:
'© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
}).addTo(map);
} else {
map.setView([lat, lon], 28);
}
const marker = L.marker([lat, lon]).addTo(map);
marker.bindPopup();
} catch (Error) {
alert(`Error: ${Error.message}`);
}
}
btn.addEventListener("click", function () {
console.log("I am working");
const input = document.getElementById("ip-input");
const inputValue = input.value;
getLocation(inputValue);
});
document.addEventListener("DOMContentLoaded", () => getLocation(""));
function updateCard(data) {
console.log(data);
console.log(data[1]);
document.getElementById("ip").textContent = data[1];
document.getElementById("location").textContent = data[3];
document.getElementById("timezone").textContent = data[0];
document.getElementById("isp").textContent = data[2];
const inputField = document.getElementById("ip-input");
inputField.value = `${data[1]}`;
}