Skip to content

Instantly share code, notes, and snippets.

@mvark
Created January 9, 2024 07:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mvark/fa3737fee7105b4183155c19ffe7a504 to your computer and use it in GitHub Desktop.
Save mvark/fa3737fee7105b4183155c19ffe7a504 to your computer and use it in GitHub Desktop.
Simple JavaScript code sample to detect location through an API call to IPAPI web service
<!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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment