Skip to content

Commit

Permalink
Show map of the IP address location
Browse files Browse the repository at this point in the history
  • Loading branch information
david-tejada committed Mar 28, 2024
1 parent ba313ba commit 0bf9db5
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 14 deletions.
21 changes: 7 additions & 14 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import L from "leaflet";
import { setMapView } from "./map";

type LocationDataError = { code: number; messages: string };
type LocationData = {
ip: number;
isp: string;
location: {
lat: number;
lng: number;
city: string;
region: string;
timezone: string;
Expand All @@ -15,17 +17,6 @@ type LocationData = {
type LocationDataResponse = LocationDataError | LocationData;

const searchForm = document.querySelector<HTMLFormElement>("#js-search");
const map = L.map("map", { zoomControl: false }).setView([51.505, -0.09], 13);
L.control
.zoom({
position: "bottomleft",
})
.addTo(map);
L.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png", {
maxZoom: 19,
attribution:
'&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
}).addTo(map);

const pIp = document.querySelector("#js-ip")!;
const pLocation = document.querySelector("#js-location")!;
Expand All @@ -46,6 +37,8 @@ function fillLocation(data: LocationDataResponse) {
pLocation.textContent = `${data.location.city}, ${data.location.region} ${data.location.postalCode}`;
pTimezone.textContent = `UTC ${data.location.timezone}`;
pIsp.textContent = data.isp;

setMapView(data.location.lat, data.location.lng);
}

async function fetchLocation(
Expand All @@ -70,7 +63,7 @@ searchForm?.addEventListener("submit", async (event) => {
fillLocation(data);
});

const userLocation = await fetchLocation();
fillLocation(userLocation);
const data = await fetchLocation();
fillLocation(data);

export {};
25 changes: 25 additions & 0 deletions src/map.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import L from "leaflet";

const locationIcon = L.icon({
iconUrl: "/icon-location.svg",
iconSize: [46, 56],
});

const map = L.map("map", { zoomControl: false });
L.control
.zoom({
position: "bottomleft",
})
.addTo(map);
L.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png", {
maxZoom: 19,
attribution:
'&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
}).addTo(map);

export function setMapView(lat: number, lng: number) {
map.setView([lat, lng], 14);
L.marker([lat, lng], {
icon: locationIcon,
}).addTo(map);
}

0 comments on commit 0bf9db5

Please sign in to comment.