-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
87 lines (75 loc) · 2.35 KB
/
script.js
File metadata and controls
87 lines (75 loc) · 2.35 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
const ipAddressEl = document.getElementById('result-ip');
const locationEl = document.getElementById('result-location');
const timezoneEl = document.getElementById('result-timezone');
const ispEl = document.getElementById('result-isp');
const formEl = document.getElementById('search-form');
let map;
async function fetchLocationData(params) {
const API_KEY = 'at_Eeh3bF7YLVsaMVy3jVacaOLBNr5Ph';
const API_URL = 'https://geo.ipify.org/api/v2/country,city';
try {
const response = await fetch(`${API_URL}?apiKey=${API_KEY}${params ?? ''}`);
const data = await response.json();
const { ip, isp } = data;
const { city, region, timezone, lat, lng } = data.location;
ipAddressEl.innerText = ip;
locationEl.innerText = `${city}, ${region}`;
timezoneEl.innerText = timezone;
ispEl.innerText = isp;
console.log(lat, lng);
initMap(lat, lng);
} catch (error) {
console.error('Error fetching IP address:', error);
}
}
function initMap(lat, lng) {
const customIcon = L.icon({
iconUrl: './images/icon-location.svg',
iconAnchor: [16, 32],
popupAnchor: [0, -32],
});
if (!map) {
map = L.map('map', { zoomControl: false }).setView([lat, lng], 13);
L.tileLayer(
'https://{s}.basemaps.cartocdn.com/rastertiles/light_all/{z}/{x}/{y}.png',
{
maxZoom: 19,
attribution: '© <a href="https://carto.com/">CartoDB</a>',
}
).addTo(map);
} else {
map.setView([lat, lng], 13);
}
map.eachLayer((layer) => {
if (layer instanceof L.Marker) {
map.removeLayer(layer);
}
});
L.marker([lat, lng], { icon: customIcon }).addTo(map);
}
function isValidDomain(domain) {
const domainRegex =
/^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/;
return domainRegex.test(domain);
}
function isValidIP(ip) {
const ipv4Regex = /^(\d{1,3}\.){3}\d{1,3}$/;
const ipv6Regex = /^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/;
return ipv4Regex.test(ip) || ipv6Regex.test(ip);
}
function handleSearch(e) {
e.preventDefault();
const searchInput = document.getElementById('search-input').value;
if (isValidDomain(searchInput)) {
fetchLocationData(`&domain=${searchInput}`);
} else if (isValidIP(searchInput)) {
fetchLocationData(`&ipAddress=${searchInput}`);
} else {
alert('Please input a valid IP or domain');
}
}
formEl.addEventListener('submit', handleSearch);
function getInitialLocation() {
fetchLocationData();
}
getInitialLocation();