在函数javascript中传递参数

时间:2016-02-06 01:37:43

标签: javascript geolocation

我正在编写一个代码,我将传递destincaiton地址,代码将自动计算当前位置的距离。

当我在代码中使用目标地址作为硬编码时,代码工作正常。它在屏幕上打印距离。

我面临的另一个问题是即使在打印结果后,页面仍然显示为连接..

有人可以告诉我如何在身体负荷上传递目的地地址吗?

以下是我用作目标的地址变量。

<!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>

0 个答案:

没有答案