Introduction
InstantGeo is a service that provides geolocation information about the current user using a lightweight javascript file. any page that has the script tag in the DOM will have access to a global geojs
object containing at-least the following information
Loading JSON...
instantgeo
is currently not available on NPM and doesn't support self hosting, it must be included on the page using the https://js.instantgeo.info
URI.
Loading Synchronously
If you have any content above the fold that relies on geo location information to render, you can load the script synchronously, please bear in mind that it might have some negligible performance impact on your site.
<script src="https://js.instantgeo.info"></script>
After the placement of this script or in DOMContentLoaded
event you can inspect the geojs
globally available object to see the available information.
console.log(geojs)
{
"longitude": "xxx",
"latitude": "xxx",
"continent": "XX",
"country": "XX",
"timezone": "Xxx/Xxx",
"city": "xxx",
"region": "xxx",
"regionCode": "XX",
"asOrganization": "xxx",
"postalCode": "xxx"
}
Loading Async (Recommended)
If the geolocation information is not render critical to your app, you can load the script asynchronously that it will have little to no impact on your page load performance, and you can bind an event to the document
to execute a function as soon as the geolocation information is available.
<!-- Load the script tag with either defer or async attribute -->
<script defer src="https://js.instantgeo.info"></script>
<!-- Wait for the `geojs-loaded` event before using the global `geojs` variable -->
<script>
document.addEventListener('geojs-loaded', function(){
console.log(geojs);
})
</script>
Using as JSON endpoint
If you don't need the geolocation information to be available globally and only want to fetch it on-demand, you can use the /json
endpoint, see example below
async function getGeoLocatinInfo() {
const response = await fetch('https://js.instantgeo.info/json');
return await response.json();
}
The /json
endpoint cannot be used on server-side as it will return the information about the server's IP address.