Zipcode-Finder/script.js

52 lines
1.2 KiB
JavaScript
Raw Normal View History

"use strict";
2023-02-06 11:17:43 +00:00
var mouseX, mouseY;
denmark.onmousemove = event => {
zip.style.display = "none";
var rect = denmark.getBoundingClientRect();
mouseX = event.x - rect.left;
mouseY = event.y - rect.top;
var coordX = mouseX / event.target.clientWidth * 8 + 6.2;
var coordY = Math.abs(mouseY / event.target.clientHeight * 3.6 - 57.93);
2023-02-06 11:17:43 +00:00
coords.innerHTML = `${coordX}<br>${coordY}`;
var oldMouseX = mouseX, oldMouseY = mouseY;
setTimeout(() => {
if (!mouseX || !mouseY || oldMouseX != mouseX || oldMouseY != mouseY) return;
var xhr = new XMLHttpRequest;
xhr.onload = () => {
if (xhr.status === 200)
eval(xhr.responseText);
else
onZipError();
}
xhr.open("GET", `https://api.dataforsyningen.dk/postnumre/reverse?x=${coordX}&y=${coordY}&callback=onZipFound`);
xhr.send();
}, 200);
};
denmark.onmouseleave = () => {
mouseX = mouseY = null;
};
function onZipFound(data) {
zip.innerHTML = `${data.nr} <b>${data.navn}</b>`;
zip.style.left = (mouseX+3) + "px";
zip.style.top = (mouseY+3) + "px";
zip.style.display = "block";
}
function onZipError() {
zip.innerHTML = "Postnummer ikke fundet";
zip.style.left = (mouseX+3) + "px";
zip.style.top = (mouseY+3) + "px";
zip.style.display = "block";
}