Introduction
It is very important for Hybrid mobile apps to get the location of customers who are using apps. With Cordova/phone gap, it's very essay to get latitude and longitude details from which you will get details about the customer country, state, city, etc.
Using the Code
- Copy code to one Notepad file.
- The code contains HTML and script parts.
- Enter the latitude and longitude values in the provided text boxes and get the location details :)
<script>
var country,state,city,pinCode;
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
function getLocationDetails()
{
hide();
latitude1=document.getElementById("latitude").value;
longitude1=document.getElementById("longitude").value;
var url="http://maps.googleapis.com/maps/api/geocode/json?latlng="+
latitude1+","+longitude1+"&sensor=true";
var xhr = createCORSRequest('POST', url);
if (!xhr) {
alert('CORS not supported');
}
xhr.onload = function() {
var data =JSON.parse(xhr.responseText);
if(data.results.length>0)
{
var locationDetails=data.results[0].formatted_address;
var value=locationDetails.split(",");
count=value.length;
country=value[count-1];
state=value[count-2];
city=value[count-3];
pin=state.split(" ");
pinCode=pin[pin.length-1];
state=state.replace(pinCode,' ');
document.getElementById("val").innerHTML=country+
" | "+state+" | "+city+" | "+pinCode;
}
else
{
document.getElementById("messageBox").style.visibility="visible";
document.getElementById("message").innerHTML=
"No location available for provided details.";
}
};
xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};
xhr.send();
}
function hide()
{
document.getElementById("messageBox").style.visibility="hidden";
}
</script>
//HTML Code
<body onload="hide()">
<div >
</div><br><br>
<div>
Latitude:<input type="text" id="latitude"><br><br>
Longitude:<input type="text" id="longitude"><br>
<br>
<input type="button" value="Get Location"
onclick="getLocationDetails()"></button>
<br><br>
<label id="val"></label>
</div>
<div id="messageBox"
style="position:fixed;top:30%;left:30%;
width:200px;height:100px;border-radius:15px;text-align:center;
background-color:skyblue;
">
<div style="position:absolute;margin-top:0px;left:2px;
height:20px;width:98%;border-radius:5px;overflow:hidden;
background-color:pink;
"><label id="title" style="
color:blue;">Skin Advisor</label></div>
<div style="position:absolute;margin:2px;top:25px;height:80px;width:100%;">
<label id="message" style="
color:blue;font-family:Helvetica;"></label></div>
</div>
</body>
Points of Interest
You can use the API in Hybrid mobile apps which use HTML, JavaScript, jQuery. In place of CORS, if you use $.ajax
service call, that will also show proper results.