2012-04-02 96 views
0

我正在嘗試查找2個點之間的距離,一個來自用戶輸入,另一個來自我的數據庫中的地址。我已經把下面的代碼放在一起,這似乎工作(我有測試變量,所以沒有數據庫正在進行測試),但是我碰到了一堵牆;我無法弄清楚爲什麼我需要點擊兩次按鈕才能顯示輸出結果?使用Google Maps API查找2個點之間的距離

任何幫助深表感謝

下面的代碼:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml"> 
    <head> 
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
    <title>Google Maps JavaScript API Example: Extraction of Geocoding Data</title> 
    <script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAA7j_Q-rshuWkc8HyFI4V2HxQYPm-xtd00hTQOC0OXpAMO40FHAxT29dNBGfxqMPq5zwdeiDSHEPL89A" type="text/javascript"></script> 
<!-- According to the Google Maps API Terms of Service you are required display a Google map when using the Google Maps API. see: http://code.google.com/apis/maps/terms.html --> 
    <script type="text/javascript"> 

//var globalAddr = new Array(); 
var globalName; 
var xmlhttp; 
var geocoder, location1, location2; 
var distanceVal; 

    function initialize() { 
     geocoder = new GClientGeocoder(); 
    } 

     function showLocation() { 
     geocoder.getLocations(document.getElementById("address1").value, function (response) { 
      if (!response || response.Status.code != 200) 
      { 
       alert("Sorry, we were unable to geocode the first address"); 
      } 
      else 
      { 
       location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address}; 
       geocoder.getLocations(document.getElementById("address2").value, function (response) { 
        if (!response || response.Status.code != 200) 
        { 
         alert("Sorry, we were unable to geocode the second address"); 
        } 
        else 
        { 
         location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address}; 
         calculateDistance(); 
        } 
       }); 
      } 
     }); 
    } 

    function calculateDistance() 
    { 

      var glatlng1 = new GLatLng(location1.lat, location1.lon); 
      var glatlng2 = new GLatLng(location2.lat, location2.lon); 
      var miledistance = glatlng1.distanceFrom(glatlng2, 3959).toFixed(1); 
      var kmdistance = (miledistance * 1.609344).toFixed(1); 

      distanceVal = miledistance; 
    } 

function loadXMLDoc(url,cfunc) 
{ 
     if (window.XMLHttpRequest) 
      {// code for IE7+, Firefox, Chrome, Opera, Safari 
      xmlhttp=new XMLHttpRequest(); 
      } 
     else 
     {// code for IE6, IE5 
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
     } 
     xmlhttp.onreadystatechange=cfunc; 
     xmlhttp.open("GET",url,true); 
     xmlhttp.send(); 
} 
function getData(str) 
     { 
     loadXMLDoc("getData.php?address="+str,function() 
      { 
       if (xmlhttp.readyState==4 && xmlhttp.status==200) 
       { 
        var x = xmlhttp.responseText; 
        var dnames = x.split("~~~"); 
        var daddr = x.split("^^^"); 
        daddr.shift(); 
        dnames.pop(); 

        var testArray = new Array('85281','18657','90210'); 

        var shortest = 999999; 

        for(var i = 0; i <= testArray.length-1; i++) 
        { 

         document.getElementById("address2").value = testArray[i];//daddr[i]; 
         showLocation(); 

         //i get a blank alert 3 times here the first time, then I get the a value the 2nd time.. makes no sense! 
         alert(distanceVal); 

         if (shortest > distanceVal) 
         { 
          shortest = distanceVal; 
          globalName = dnames[i]; 
         } 

        } 

        document.getElementById("results").innerHTML = globalName + " " + shortest; 

       } 
      }) 
     } 

    </script> 
    </head> 

    <body onload="initialize()"> 

    <form> 
     <p> 
     <input type="text" id="address1" name="address1" class="address_input" size="40" /> 
     <input type="hidden" id="address2" name="address2" /> 
     <input type="hidden" id="distance" name="distance" /> 
     <input type="button" name="find" value="Search" onclick="getData(document.getElementsByName('address1')[0].value)"/> 
     </p> 
    </form> 
    <p id="results"></p> 

    </body> 
</html> 

回答

2

當您在getData()回撥電話showLocation(),這臺假兩個地理編碼器調用,如果兩者都成功呼叫calculateDistance()

但是,這兩個地理編碼調用都需要時間。第一個getLocations()引發了地理編碼請求,並讓它繼續,並在其回調中處理。在這個函數中,還有另一個請求在它自己的回調中處理。

雖然那些正在等待結果,但代碼執行仍在繼續,並且即使尚未調用calculateDistance(),也已達到alert(distanceVal)。因此distanceVal尚未設置。

當您再次單擊該按鈕,全球distanceVal將已通過所有的回調函數填充,所以(即使第二組地理編碼/回調有完成),它必須顯示的值。但是,如果您更改要測試的值,則會發現它顯示的舊值現在不正確。

一切這取決於在回調函數發現值必須該回調函數中進行處理。如果將數據顯示移動到calculateDistance(),則一切都會正常,因爲數據可用於該功能。

+0

謝謝安德魯,我拉着我的頭髮試圖讓它工作,這完全有道理。 – bruchowski 2012-04-03 15:14:47

相關問題