How to Get Visitor's Location (I.E. Country) Using Geolocation

How to get visitor's location (i.e. country) using geolocation?

You don't need to locate the user if you only need their country. You can look their IP address up in any IP-to-location service (like maxmind, ipregistry or ip2location). This will be accurate most of the time.

Here is a client-side example with Ipregistry (disclaimer, I am working for):

fetch('https://api.ipregistry.co/?key=tryout')
.then(function (response) {
return response.json();
})
.then(function (payload) {
console.log(payload.location.country.name + ', ' + payload.location.city);
});

If you really need to get their location, you can get their lat/lng with that method, then query Google's or Yahoo's reverse geocoding service.

How can I find a user’s country using HTML5 geolocation?

    var geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': <YOURLATLNGRESPONSEFROMGEO>}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var loc = getCountry(results);
}
}
});

function getCountry(results)
{
for (var i = 0; i < results[0].address_components.length; i++)
{
var shortname = results[0].address_components[i].short_name;
var longname = results[0].address_components[i].long_name;
var type = results[0].address_components[i].types;
if (type.indexOf("country") != -1)
{
if (!isNullOrWhitespace(shortname))
{
return shortname;
}
else
{
return longname;
}
}
}

}

function isNullOrWhitespace(text) {
if (text == null) {
return true;
}
return text.replace(/\s/gi, '').length < 1;
}

This is what I use :)

How to detect browser country in client site?

There are multiple options to determine the locale. In descending order of usefulness, these are:

  1. Look up the IP address, with an IP geolocation service like Maxmind GeoIP. This is the location the request is coming from, i.e. if an American vacations in Italy and uses a Swedish VPN, it will return Sweden.

It can only be done with the help of the server. The main advantage is that it's very reliable. The accuracy will be country or region for free services, city or region for paid ones.


  1. Look up the precise location on Earth from the browser with the geolocation API. An American vacationing in Italy using a Swedish VPN will register as Italy.

The answer will be very precise, usually no more than 10m off. In principle, it could work client-side, although you may want to perform the coordinate -> country lookup on the server. The main disadvantages are that not all devices have either GPS or WiFi position, and that it generally requires explicit user consent.


  1. Look in the Accept-Language header on the server (or with the help of the server), and extract the locale information. An American vacationing in Italy using a Swedish VPN will register as USA.

The downside is that this is a setting that's extremely easy to change. For instance, English speakers around the world may prefer en-US settings in order to avoid machine-translated text. On modern browsers (as of writing not IE/Edge, and only Safari 11+), you can also request navigator.languages.


  1. navigator.language is the first element of the navigator.languages header. All of the considerations of navigator.languages apply. On top, this information can sometimes be just the language without any locale (i.e. en instead of en-US).

  2. Use another, third-party service. For instance, if the user signs in via a Single-Sign-On system such Facebook connect, you can request the hometown of the user. This information is typically very unreliable, and requires a third party.

Use Geolocation Show Nearest Location to Web Visitor using JavaScript (COMBINING SCRIPTS)

Attached is the solution I was looking for in the event anyone else is in the same predicament. Keep in mind, this will only function if you have a valid SSL certificate on your HTML 5 website.

var lat = 0;var lng = 0;function geoFindMe() {
const status = document.querySelector('#status'); const mapLink = document.querySelector('#map-link');
mapLink.href = ''; mapLink.textContent = '';
function success(position) { const latitude = position.coords.latitude; const longitude = position.coords.longitude;
status.textContent = ''; mapLink.href = ``; mapLink.textContent = ``; lat = position.coords.latitude; lng = position.coords.longitude; showNearestLocations(); }
function error() { status.textContent = 'Unable to retrieve your location'; }
if (!navigator.geolocation) { status.textContent = 'Geolocation is not supported by your browser'; } else { status.textContent = 'Locating…'; navigator.geolocation.getCurrentPosition(success, error); }
}
document.querySelector('#find-me').addEventListener('click', geoFindMe);

function distance(lat1, lon1, lat2, lon2, unit) { var radlat1 = Math.PI * lat1/180 var radlat2 = Math.PI * lat2/180 var theta = lon1-lon2 var radtheta = Math.PI * theta/180 var dist = Math.sin(radlat1) *Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta); if (dist > 1) { dist = 1; } dist = Math.acos(dist) dist = dist * 180/Math.PI dist = dist * 60 * 1.1515 if (unit=="K") { dist = dist * 1.609344 } if (unit=="N") { dist = dist * 0.8684 } return dist }
function showNearestLocations() { var data = [{ "lat": 36.5983825, "lng": -82.1828577, "location": "Bristol", "link": "bristol", }, { "lat": 36.7053664, "lng": -81.999551, "location": "Abingdon", "link": "abingdon", }, { "lat": 35.9120595, "lng": -84.0979276, "location": "West Knoxville", "link": "west-knoxville", }, { "lat": 35.8718708, "lng": -83.5642387, "location": "Sevierville", "link": "sevierville", }];
var html = ""; var poslat = lat; var poslng = lng; var found = false; for (var i = 0; i < data.length; i++) { // if this location is within 0.1KM of the user, add it to the list if (distance(poslat, poslng, data[i].lat, data[i].lng, "M") <= 20) { html += '<a href="/' + data[i].link + '" target="_blank"><i class="icon-location"></i>' + data[i].location + '</a> '; found = true; } } $('#nearestLocation').html(html); if (!found) { $('#nearestLocation').html("no near location found"); }}
#map-link {  display: none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><button id = "find-me">Show my nearest locations</button> <span id="nearestLocation"></span><p id = "status"></p><a id = "map-link" target="_blank"></a>

Get visitors language & country code with javascript (client-side)

navigator.language isn't reliable as one of your linked questions states.

The reason this is asked a lot, but you're still searching says something about the problem. That language detection purely on the client side is not anything close to reliable.

First of all language preferences should only be used to detect language preferences - i.e. not location. My browser is set to en_US, because I wanted the English version. But I'm in the UK, so would have to alter this to en_GB to have my country detected via my browser settings. As the 'customer' that's not my problem. That's fine for language, but no good if all the prices on your site are in $USD.

To detect language you really do need access to a server side script. If you're not a back end dev and want to do as much as possible on the client side (as your question), all you need is a one line PHP script that echos back the Accept-Language header. At its simplest it could just be:

<?php
echo $_SERVER['HTTP_ACCEPT_LANGUAGE'];
// e.g. "en-US,en;q=0.8"

You could get this via Ajax and parse the text response client side, e.g (using jQuery):

$.ajax( { url: 'script.php', success: function(raw){
var prefs = raw.split(',');
// process language codes ....
} } );

If you were able to generate your HTML via a back end, you could avoid using Ajax completely by simply printing the language preferences into your page, e.g.

<script>
var prefs = <?php echo json_encode($_SERVER['HTTP_ACCEPT_LANGUAGE'])?>;
</script>

If you had no access to the server but could get a script onto another server, a simple JSONP service would look like:

<?php
$prefs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
$jsonp = 'myCallback('.json_encode($prefs).')';

header('Content-Type: application/json; charset=UTF-8', true );
header('Content-Length: '.strlen($jsonp), true );
echo $jsonp;

Using jQuery for your Ajax you'd do something like:

function myCallback( raw ){
var prefs = raw.split(',');
// process language codes ....
}
$.ajax( {
url: 'http://some.domain/script.php',
dataType: 'jsonp'
} );

Country detection is another matter. On the client side there is navigator.geolocation, but it will most likely prompt your user for permission, so no good for a seamless user experience.

To do invisibly, you're limited to geo IP detection. By the same token as above, don't use language to imply country either.

To do country detection on the client side, you'll also need a back end service in order to get the client IP address and access a database of IP/location mappings. Maxmind's GeoIP2 JavaScript client appears to wrap this all up in a client-side bundle for you, so you won't need your own server (although I'm sure it will use a remote jsonp service). There's also freegeoip.net, which is probably less hassle than MaxMind in terms of signing up, and it appears to be open source too.

How to get location of website visitor without depending on JavaScript, since it will not work unless user allow it

It's possible to get location by using IP address of visitor. Use web-service provided by ipinfodb.com :

            string url = string.Format("https://api.ipinfodb.com/v3/ip-city/?key={0}&ip={1}&format=json", APIKey, ipAddress);
using (WebClient client = new WebClient())
{
string json = client.DownloadString(url);
Location location = new JavaScriptSerializer().Deserialize<Location>(json);
return location;
}


Related Topics



Leave a reply



Submit