2013-12-23 22 views
0

我有一個腳本,允許用戶查看通信機櫃的位置。我試圖讓HTML5通過經度和緯度的PHP腳本(geo.php)來更新與地圖座標數據庫中的記錄,但要得到錯誤:在另一個功能中使用地理位置

ReferenceError: Can't find variable: pos

這是我的代碼。

function getLocation() { 
      navigator.geolocation.getCurrentPosition(function(pos) 
      { 
       var lat = pos.coords.latitude; 
       var lng = pos.coords.longitude; 

      }); 
} 

function saveLocation(building, commNo) { 
      getLocation(); 
      var latitude = lat; 
      var longitude = lng; 
      alert(latitude + longitude); 
      document.getElementById('maps').innerHTML = 'Saving <img src=\"img/ui-anim_basic_16x16.gif\">'; 
      var strURL = "includes/geo.php?building=" + building + "&commNo=" + commNo + "&latlng=" + latitude + "," + longitude; 

var req = getXMLHTTP(); 
      if (req) { 

       req.onreadystatechange = function() { 
        if (req.readyState == 4) { 
         // only if "OK" 
         if (req.status == 200) { 
          getMap(exchangeName, PCP); 
         } else { 
          alert("There was a problem while using XMLHTTP:\n" + req.statusText); 
         } 
        } 
       } 
       req.open("GET", strURL, true); 
       req.send(null); 
      } 

     } 

回答

1

的地理位置API是異步的,就像你的Ajax調用,所以你必須等待結果返回,並請幫我把經緯度出現在鏈接到由AJAX調用即使您必須等待異步調用,變量也只能在定義範圍內使用。

function getLocation(callback) { 
    navigator.geolocation.getCurrentPosition(function (pos) { 
     callback(pos.coords.latitude, pos.coords.longitude); 
    }); 
} 

function saveLocation(building, commNo) { 
    getLocation(function(latitude, longitude) { 
     document.getElementById('maps').innerHTML = 'Saving <img src=\"img/ui-anim_basic_16x16.gif\">'; 
     var strURL = "includes/geo.php?building=" + building + "&commNo=" + commNo + "&latlng=" + latitude + "," + longitude; 

     var req = getXMLHTTP(); 
     if (req) { 

      req.onreadystatechange = function() { 
       if (req.readyState == 4) { 
        // only if "OK" 
        if (req.status == 200) { 
         getMap(exchangeName, PCP); 
        } else { 
         alert("There was a problem while using XMLHTTP:\n" + req.statusText); 
        } 
       } 
      } 
      req.open("GET", strURL, true); 
      req.send(null); 
     } 
    }); 
} 
+0

謝謝!這工作的一種享受,腳本現在功能齊全!感謝您抽出時間回覆 :) – dumbterminal