You can use Google's geolocation API to get the lat and lon based on the user's IP address:
var apiKey = "Your Google API Key";
function findLatLonFromIP() {
return new Promise((resolve, reject) => {
$.ajax({
url: `https://www.googleapis.com/geolocation/v1/geolocate?key=${apiKey}`,
type: 'POST',
data: JSON.stringify({considerIp: true}),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: (data) => {
if (data && data.location) {
resolve({lat: data.location.lat, lng: data.location.lng});
} else {
reject('No location object in geolocate API response.');
}
},
error: (err) => {
reject(err);
},
});
});
}
Then you can use these coordinates to get the address of the user using the geocoding API. Here is an example that returns the country:
function getCountryCodeFromLatLng(lat, lng) {
return new Promise((resolve, reject) => {
$.ajax({
url: `https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lng}&key=${apiKey}`,
type: 'GET',
data: JSON.stringify({considerIp: true}),
dataType: 'json',
success: (data) => {
console.log('reverse geocode:', data.results[0].address_components);
data.results.some((address) => {
address.address_components.some((component) => {
if (component.types.includes('country')) {
return resolve(component.short_name);
}
});
});
reject('Country not found in location information.');
},
error: (err) => {
reject(err);
},
});
});
}
Above, just look through the data.results
to find the information you need (City, Street, Country etc...)
Use these two functions above together:
findLatLonFromIP().then((latlng) => {
return getCountryCodeFromLatLng(latlng.lat, latlng.lng);
}).then((countryCode) => {
console.log('User\'s country Code:', countryCode);
});