I am writing a code inwhich I will pass the destincaiton address and code will calculate the distance from current location automatically.
Code is working fine when I am using destination address as hardcoded inside the code. It prints the distance on screen.
One more problem I am facing is even after printing the result, page still showing as connecting..
Can anybody please tell me how to pass the destination address on body load?
Below is the address variable which I am using as target.
<!DOCTYPE html>
<html>
<body onLoad="getLocation()">
<p>Please Wait</p>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<!--
<button onclick="getLocation()">Try It</button>
-->
<p id="demo"></p>
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
var geocoder = new google.maps.Geocoder();
var address = "Reading UK";
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
var R = 6371;
var dLat = (latitude-position.coords.latitude) * (Math.PI/180);
var dLon = (longitude-position.coords.longitude) * (Math.PI/180);
var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos((position.coords.latitude) * (Math.PI/180)) * Math.cos((latitude) * (Math.PI/180)) * Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
function displayLocation(latitude,longitude,distance,adr){
var request = new XMLHttpRequest();
var method = 'GET';
var sourcelocation = "london";
var url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='+latitude+','+longitude+'&sensor=true';
var async = true;
request.open(method, url, async);
request.onreadystatechange = function(){
if(request.readyState == 4 && request.status == 200){
var data = JSON.parse(request.responseText);
var address = data.results[0];
//sourcelocation = address.formatted_address;
document.write("Source Location :"+address.formatted_address+"<BR>Destination Address:"+adr+"<BR>Distance:"+distance);
}
};
var retresults = "Source Location :"+address.formatted_address+" Destination Address:"+adr+" Distance:"+distance;
request.send();
return retresults;
};
var adr = address;
var home = displayLocation(position.coords.latitude,position.coords.longitude,d.toFixed(2),adr);
// alert(home);
}
});
}
</script>
</body>
</html>