Introduction
Examples
InstantGeo offers a simple API that you can use to get the location of an IP address. currently we are only offering GeoIP lookup for the IP address of the requesting client, which means that you can't use InstantGeo server side.
1. Redirect US users to a different page
<script async src="https://js.instantgeo.info"></script>
<script>
document.addEventListener('geojs-loaded', () => {
if(geojs.country === 'US') {
window.location.href = 'https://us.example.com'
}
});
</script>
2. Update site language based on user location
<script>
fetch('https://js.instantgeo.info/json')
.then(response => response.json())
.then(data => {
if (data.country === 'US') {
document.documentElement.lang = 'en-US'
} else {
document.documentElement.lang = 'en-GB'
}
});
</script>
3. Cache user location in localStorage for even faster subsequent updates
async function getGeoIPData() {
const data = localStorage.getItem('geojs');
if (data) {
return new Promise(resolve => resolve(JSON.parse(data)));
}
const response = await fetch('https://js.instantgeo.info/json');
const json = await response.json();
localStorage.setItem('geojs', JSON.stringify(json));
return json;
}
const data = await getGeoIPData();
4. Get user location in a React app
npm install react-instantgeo
import useGeoInfo from 'react-instantgeo';
export default function App() {
const { data, loading, error } = useGeoInfo();
if (loading) {
return <div>Loading...</div>;
}
if (error) {
return <div>Error: {error.message}</div>;
}
return (
<div>
<h1>Country: {data.country}</h1>
<h1>City: {data.city}</h1>
<h1>Latitude: {data.latitude}</h1>
<h1>Longitude: {data.longitude}</h1>
</div>
);
}