
This article shows how HTML5 Geolocation API is very simple and easy to use. We have provided sample code and Demo below. To detect the location of a client in the past, one would typically have to inspect the client IP address and make a reasonable guess for user geographic location.
Related article on DGlobalTech.com
- Flash versus HTML5
- HTML5 – Video and Audio File formats and browser support
- HTML Javascript online Realtime Editor
However, as part of the HTML5 efforts, the W3C has developed a set of APIs to effectively allow the client-side browsers to retrieve geographic positioning information with JavaScript.
- Check if user browser supports API or not
- Function to find user geolocation, if user browser supports the api.
- Display user geo location in map
Code To Check Browser Support to Geolocation API:
function getuserLocation() {
if (navigator.geolocation) {
x.innerHTML="Geolocation API is supported by this browser.";
}
else{
x.innerHTML="Geolocation API is not supported by this browser.";
}
}
function showuserPosition(position) {
x.innerHTML="Latitude: " + position.coords.latitude +
"Longitude: " + position.coords.longitude;
}
Code To Display User Location in Map:
function showPosition(position) {
var latlon=position.coords.latitude+","+position.coords.longitude;
var img_url="http://maps.googleapis.com/maps/api/staticmap?center="
+latlon+"&zoom=14&size=400x300&sensor=false";
document.getElementById("mapholder").innerHTML="<img src='"+img_url+"'>";
}
Putting All togather to display user’s location
Copy Paste this code to display user location in Map:
<!DOCTYPE html>
<html>
<body>
<p id="userdemo">Get User Location Demo:</p>
<button onclick="getuserLocation()"> Test Location</button>
<div id="mapholder"></div>
<script>
var x=document.getElementById("userdemo");
function getuserLocation(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showuserPosition,showbrowserError);
}
else{
x.innerHTML="Geolocation is not supported by this browser.";
}
}
function showuserPosition(position) {
var latlon=position.coords.latitude+","+position.coords.longitude;
var img_url="http://maps.googleapis.com/maps/api/staticmap?center="
+latlon+"&zoom=14&size=400x300&sensor=false";
document.getElementById("mapholder").innerHTML="<img src='"+img_url+"'>";
}
function showbrowserError(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>
</script>
</body>
</html>
View demo page to test user location display in map:
READ : jQuery Interview Questions and Answers : 15 commonly asked Questions
READ : SQL Interview Questions and Answers
READ : HTML5 Interview Questions and Answers : 10 Commonly asked Questions