For some web-applications, we need to get user location, so to that, we can use javascript with various api's to get Lat/long and convert it into address or Location, and we can also use HTML 5 Gelocation(not supported by old browsers) .
Get user location using Javascript
One of the easiet way, without asking user for permissions, we can get IP address lookup and get user details using http://ip-api.com/ , https://ipinfo.io , geoip-db.com etc They provide the data in various formats too (JSON/XML/CSV…).
Here is the simple example, where I am using https://ipinfo.io
<div id="IP">
</div>
<div id="Country">
</div>
<div id="loc">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function ipLookUp () {
$.ajax({
url: 'https://ipinfo.io',
dataType: 'jsonp',
jsonp: 'callback',
})
.then(
function success(response) {
$("#IP").html(response.ip);
$("#Country").html(response.country);
$("#loc").html(response.loc);
console.log(response.ip, response.country,response.loc);
},
function fail(data, status) {
console.log('Request failed. Returned status of',
status);
}
);
}
ipLookUp()
</script>
Output:
Here is the fiddle link for you to test.
Note: One of the drawback of the above approach is, above provided co-ordinates may not be accurate, although country is always correct, also for large number of requests, you need to pay for this service unlike HTML5 Gelocation API (explained below in this article).
Once you have the Latitude, longitude of the user, you need to apply Reverse Geocoding technique to get address of the user, so after creating reverse geocoding function, here is the complete code (Please use your Google maps API key for testing)
<div id="IP">
</div>
<div id="Country">
</div>
<div id="loc">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function ipLookUp () {
$.ajax({
url: 'https://ipinfo.io',
dataType: 'jsonp',
jsonp: 'callback',
})
.then(
function success(response) {
$("#IP").html(response.ip);
$("#Country").html(response.country);
$("#loc").html(response.loc);
console.log(response.loc.split(',')[0],response.loc.split(',')[0]);
//Call reverse Geocode
getAddress(response.loc.split(',')[0],response.loc.split(',')[0]);
},
function fail(data, status) {
console.log('Request failed. Returned status of',
status);
}
);
}
function getAddress (latitude, longitude) {
$.ajax('https://maps.googleapis.com/maps/api/geocode/json?
latlng=' + latitude + ',' + longitude + '&key=' +
GOOGLE_MAP_KEY)
.then(
function success (response) {
console.log('User\'s Address Data is ', response)
},
function fail (status) {
console.log('Request failed. Returned status of',
status)
}
)
}
ipLookUp()
</script>
Note: It is better to use HTML5 geolocation API and get exact user location, if this fails(as older browser like IE 9 doesn't support it) you can get location using above Javascript/JQuery code.
Get user location using HTML5 Geolocation
The HTML Geolocation API is used to get the geographical position of a user, but before you get user's location you need to ask user for permissions.
In the HTML 5 getCurrentPosition() method is used to return the user's position, here is the sample method which is used to return location of user
navigator.geolocation.getCurrentPosition(function(location) {
console.log(location.coords.latitude);
console.log(location.coords.longitude);
console.log(location.coords.accuracy);
});
So the complete code to get Lat/long of the user would be
<!DOCTYPE html>
<html>
<body>
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Get Lat/Long</button>
<p id="demo"></p>
<script>
var x = document.getElementById("demo");
//function to getLocation using HTML5 geolocation
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
//positions passed here, check lat/long and show it to user
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
</body>
</html>
try the fiddle here, by opening it new tab, it will give you, your location's lat/long.(if needed you can reverse gocode to as explained above to get address or show it in map)
The getCurrentPosition() method returns an object on success. The latitude, longitude and accuracy properties are always returned.
To get the real word example of the this, you can use the below HTML/Javascript code with your Google api key(do not forget to enable Javascript locations api in google console)
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<button onclick="getLocation()">Get Location</button>
<div id="mapholder"></div>
<!--https://developers.google.com/maps/documentation/javascript/get-api-key-->
<script src="https://maps.google.com/maps/api/js?key=YourAPIKey"></script>
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var latlon = new google.maps.LatLng(lat, lon)
var mapholder = document.getElementById('mapholder')
mapholder.style.height = '250px';
mapholder.style.width = '500px';
var myOptions = {
center:latlon,zoom:14,
mapTypeId:google.maps.MapTypeId.ROADMAP,
mapTypeControl:false,
navigationControlOptions:{style:google.maps.NavigationControlStyle.SMALL}
}
var map = new google.maps.Map(document.getElementById("mapholder"), myOptions);
var marker = new google.maps.Marker({position:latlon,map:map,title:"You are here!"});
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}
</script>
</body>
</html>
The other useful Geolocation object methods are:
- Geolocation.watchPosition() - This method returns the current position of the user and continues to return updated position as the user moves (like the GPS enabled in your mobile app or car).
- Geolocation.clearWatch() - Stops the watchPosition() method.