JavaScript and Geolocation
In our JavaScript, we can use getCurrentPosition() method to obtain user’s current location, but first, we need to know whether Geolocation API is available in the browser before we can continue.
Geolocation API is an important feature available in modern HTML5 web browsers, which allows us to request current location of the user using JavaScript, the location information is represented by latitude and longitude coordinates. For privacy reasons, the user permission is required to access its location information.
<p><button onclick="getLocation()">Get My Location</button></p>
<p id="demo"></p>
<script src="http://maps.google.com/maps/api/js?key=AIzaSyCiRgLZ_8pFomu9f-7TEzhsgQmY4Q-c11c"></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){
lat=position.coords.latitude;
lon=position.coords.longitude;
displayLocation(lat,lon);
}
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;
}
}
function displayLocation(latitude,longitude){
var geocoder;
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(latitude, longitude);
geocoder.geocode(
{'latLng': latlng},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var add= results[0].formatted_address ;
var value=add.split(",");
count=value.length;
country=value[count-1];
state=value[count-2];
city=value[count-3];
x.innerHTML = "state name is: " + state ;
<!--Below method is used to remove PIN Code from the String using Regex method. You can use an online tool to customize your String. https://txt2re.com/index-javascript.php3?s=Uttar%20Pradesh%20201301&11&4-->
var txt=state;
var re4='(\\s+)'; // White Space 1
var re5='(\\d+)'; // Integer Number 1
var p = new RegExp(re4+re5,["i"]);
var m = p.exec(txt);
if (m != null)
{
var ws1=m[1];
var int1=m[2];
var remove = ws1 + int1;
<!-- document.write("("+ws1.replace(/</,"<")+")"+"("+int1.replace(/</,"<")+")"+"\n"); -->
var res = txt.replace(remove, "");
x.innerHTML = "state name is: " + res ;
}
}
else {
x.innerHTML = "address not found";
}
}
else {
x.innerHTML = "Geocoder failed due to: " + status;
}
}
);
}
</script>
No comments:
Post a Comment
Thanks for the comments. I`ll get back to you shortly.
Regards
Tushar