How to Find a User's Country Using HTML5 Geolocation

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 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.

getting users geolocation via html5 and javascript

Here is a script (geolocator.js) I wrote some time ago and updated recently.

Update: Geolocator v2 is released.

Features:

  • HTML5 geolocation (by user permission)
  • Location by IP
  • Geocoding (coordinates from address)
  • Reverse Geocoding (address lookup from coordinates)
  • Full address information (street, town, neighborhood, region,
    country, country code, postal code, etc...)
  • Fallback mechanism (from HTML5-geolocation to IP-geo lookup)
  • Watch geographic position
  • Get distance matrix and duration
  • Calculate distance between two geographic points
  • Get timezone information
  • Get client IP
  • Supports Google Loader (loads Google Maps dynamically)
  • Dynamically creates Google Maps (with marker, info window, auto-adjusted zoom)
  • Non-blocking script loading (external sources are loaded on the fly without interrupting page load)

See a live demo.

See API documentation.

Geolocator Example Screenshot

Usage:

var options = {
enableHighAccuracy: true,
timeout: 6000,
maximumAge: 0,
desiredAccuracy: 30, // meters
fallbackToIP: true, // get location by IP if geolocation fails or rejected
addressLookup: true, // requires Google API key
timezone: true, // requires Google API key
map: "my-map" // creates a Google map. requires Google API key
};
geolocator.locate(options, function (err, location) {
console.log(err || location);
});

Example Output:

{
coords: {
latitude: 37.4224764,
longitude: -122.0842499,
accuracy: 30,
altitude: null,
altitudeAccuracy: null,
heading: null,
speed: null
},
address: {
commonName: "",
street: "Amphitheatre Pkwy",
route: "Amphitheatre Pkwy",
streetNumber: "1600",
neighborhood: "",
town: "",
city: "Mountain View",
region: "Santa Clara County",
state: "California",
stateCode: "CA",
postalCode: "94043",
country: "United States",
countryCode: "US"
},
formattedAddress: "1600 Amphitheatre Parkway, Mountain View, CA 94043, USA",
type: "ROOFTOP",
placeId: "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
timezone: {
id: "America/Los_Angeles",
name: "Pacific Standard Time",
abbr: "PST",
dstOffset: 0,
rawOffset: -28800
},
flag: "//cdnjs.cloudflare.com/ajax/libs/flag-icon-css/2.3.1/flags/4x3/us.svg",
map: {
element: HTMLElement,
instance: Object, // google.maps.Map
marker: Object, // google.maps.Marker
infoWindow: Object, // google.maps.InfoWindow
options: Object // map options
},
timestamp: 1456795956380
}

Given the lat/long coordinates, how can we find out the city/country?

The free Google Geocoding API provides this service via a HTTP REST API. Note, the API is usage and rate limited, but you can pay for unlimited access.

Try this link to see an example of the output (this is in json, output is also available in XML)

https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true

Get a user's State with Geolocation

Here's a couple of examples in JavaScript and JSON (with the help of jQuery) using both the IP lookup method (with the help of IPinfoDB) and the Geolocation API method (with the help of Google Maps API and YQL).

In both examples I'm retrieving the region and country but there are several values you can choose from. Be aware these examples don't do any error handling and here they are edited for brevity, otherwise see the full demo.

IP Lookup in JavaScript

This method is good because it's easy to implement and is fairly accurate at a country level but accuracy drops considerably for anything more specific.

// API key excluded for brevity, see full demo.
var apiurl = 'http://api.ipinfodb.com/v3/ip-city';
$.getJSON(apiurl+'/format=json&callback=?',
function(data){
$("h3#location").html(data.regionName + ", " + data.countryName);
}
);

Geolocation API

Although by no means perfect, this method is as accurate as it gets. User is prompted to share geolocation details which may reduce usage.

navigator.geolocation.getCurrentPosition(function(pos){
$.getJSON(apiurl+'/format=json&callback=?',
function(data){
var regionName = data[...]AdministrativeAreaName;
var countryName = data[...]CountryName;
$("h3#location").html(regionName + ", " + countryName);
}
);
});

In there you'll see I used the Google Maps API v3 by way of YQL so that a JSON callback is possible.

Full demo: http://jsfiddle.net/ZjXXh

How to get City and Country using HTML5 Geolocation without relying on Google API?

The only location info you can get from geolocation api is longitude and latitude. However, you could use this info to query a database and return the info you need. There are many free geo location databases on the internet. Google "free geolocation database" and just use any that you see fit. They usually come in a big data file that you need to import to your own database. After that, you just can just call your own ajax service to get results fast and free.
Alternatively, you can find the location by using their IP, if you need to code this on the server and not the client, again, there are free IP databases for this, too. I've used http://www.ipligence.com/ to query IP locations and it worked fine. They have free version.

Getting country code from Google Maps and HTML 5 GeoLocation

Try this:

<html>

<head>
<script src="http://maps.google.com/maps/api/js?sensor=true" type="text/javascript"></script>
<script type="text/javascript">

if (navigator.geolocation) {

navigator.geolocation.getCurrentPosition(function(position) {

var lat = position.coords.latitude;
var lng = position.coords.longitude;

var latlng = new google.maps.LatLng(lat, lng);

var geocoder = new google.maps.Geocoder();

geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
alert(results[7].formatted_address);
}
} else {
alert("Geocoder failed due to: " + status);
}
});
});
} else {
alert("Geolocation services are not supported by your browser.");
}

</script>
</head>
<body>
</body>
</html>

Get city name using geolocation

You would do something like that using Google API.

Please note you must include the google maps library for this to work. Google geocoder returns a lot of address components so you must make an educated guess as to which one will have the city.

"administrative_area_level_1" is usually what you are looking for but sometimes locality is the city you are after.

Anyhow - more details on google response types can be found here and here.

Below is the code that should do the trick:

<!DOCTYPE html> 
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Reverse Geocoding</title>

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;

if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}

function errorFunction(){
alert("Geocoder failed");
}

function initialize() {
geocoder = new google.maps.Geocoder();

}

function codeLatLng(lat, lng) {

var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results)
if (results[1]) {
//formatted address
alert(results[0].formatted_address)
//find country name
for (var i=0; i<results[0].address_components.length; i++) {
for (var b=0;b<results[0].address_components[i].types.length;b++) {

//there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
//this is the object you are looking for
city= results[0].address_components[i];
break;
}
}
}
//city data
alert(city.short_name + " " + city.long_name)

} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
</script>
</head>
<body onload="initialize()">

</body>
</html>


Related Topics



Leave a reply



Submit