HOW TO Track the Location of a User via JavaScript
ipapi is an IP Location API that can fetch the location of a user - their city, country, Latitude / Longitude based on the IP address it detects from the browser making the function call. It can also get the Time Zone, Calling Code, Currency among other things.
Here's a minimal JavaScript code sample showing Geolocation with IPAPI API -
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Location Detection</title> | |
</head> | |
<body> | |
<div id="userDetails"></div> | |
<script> | |
//Define an asynchronous function called fetchData() | |
//The async keyword is used to indicate that the function contains asynchronous operations, | |
//it allows the use of the await keyword inside the function. | |
async function fetchData(url) { | |
//try-catch block helps catch and handle errors in a more structured manner. | |
try { | |
//fetch function to make an HTTP request to 'https://ipapi.co/json/'. | |
//The await keyword is used to pause the execution of the function until the Promise returned by fetch is resolved. | |
//It waits for the response from the server. | |
const response = await fetch(url); | |
if (!response.ok) { | |
throw new Error(`Failed to fetch data. Status: ${response.status}`); | |
} | |
//This line extracts the JSON body content from the HTTP response using the json method. | |
//It returns a Promise that resolves to the parsed JSON data. | |
return response.json(); | |
} catch (error) { | |
console.error('Error fetching data:', error.message); | |
throw error; | |
} | |
} | |
function displayDetails(data) { | |
let details = ""; | |
if (data.error) { | |
// If there is an error, display an error message | |
details += `<h2>Error</h2><p>${data.error}</p>`; | |
} else { | |
//The values are dynamically inserted from the userData object using ES6 template literals (the backticks & ${...} syntax). | |
details += ` | |
<h2>Your Details as captured by ipapi via JavaScript:</h2> | |
<p>IP Address: ${data.ip}</p> | |
<p>City: ${data.city}</p> | |
<p>Region: ${data.region}</p> | |
<p>Country: ${data.country_name}</p> | |
<p>Latitude: ${data.latitude}</p> | |
<p>Longitude: ${data.longitude}</p> | |
<p>Internet Provider: ${data.org}</p> | |
`; | |
} | |
//Sets the inner HTML content of that element to the constructed details string, | |
//effectively displaying the user details on the webpage. | |
document.getElementById('userDetails').innerHTML = details; | |
} | |
// Fetch and display details | |
async function fetchAndDisplayDetails() { | |
const apiURL = '//ipapi.co/json/'; | |
try { | |
const data = await fetchData(apiURL); | |
displayDetails(data); | |
} catch (error) { | |
console.error(error); | |
//This block is calling the displayDetails function and passing an object as an argument. | |
//The object has a property named error with the value "Could not fetch details." | |
displayDetails({ | |
error: "Could not fetch details." | |
}); | |
} | |
} | |
//This line calls the fetchAndDisplayDetails function, | |
//initiating the process of fetching user details and displaying them on the webpage. | |
fetchAndDisplayDetails(); | |
</script> | |
</body> | |
</html> |
Also see - Public APIs you can use
Comments
Post a Comment