2012-08-28 40 views
1

FindMyLocation定義如下:使用位置從W3C地理返回

function FindMyLocation(callback) { 
if (navigator.geolocation) { 

    var locationMarker = null; 
    if (locationMarker) { 
     return; 
    } 
    navigator.geolocation.getCurrentPosition(
     function(position){ 
      pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude); 
      map.setCenter(new google.maps.LatLng(position.coords.latitude,position.coords.longitude)); 
      addMarker(
      position.coords.latitude, 
      position.coords.longitude, 
      "You are here" 
      ); 
      setTimeout(function(window) { 
       callback.call(pos); 
      }, 1000); 
     }, 
     function (geoPositionError) { 
     switch (geoPositionError.code) { 
      case 0: 
       alert('An unknown error occurred, sorry'); 
       break; 
      case 1: 
       alert('Permission to use Geolocation was denied'); 
       break; 
      case 2: 
       alert('Couldn\'t find you...'); 
       break; 
      case 3: 
       alert('The Geolocation request took too long and timed out'); 
       break; 
      default: 
     } 
    }, 
    timeoutCallback, 10, {maximumAge:60000, timeout:50000, enableHighAccuracy:true} 
    ); 

var positionTimer = navigator.geolocation.watchPosition(
    function(position){ 
     updateMarker(
      locationMarker, 
      position.coords.latitude, 
      position.coords.longitude, 
      "Updated/Accurate Position" 
     ); 
    } 
); 
setTimeout(
    function(){ 
     // Clear the position watcher. 
     navigator.geolocation.clearWatch(positionTimer); 
    }, 
    (1000 * 60 * 5) 
); 

} else { 
    alert("Your phone browser doesn't support geolocation."); 
} 
} 
function timeoutCallback(){ 
    alert('Hi there! we are trying to locate you but you have not answered the security question yet.\n\nPlease choose "Share My Location" to enable us to find you.'); 
} 

我有這樣的代碼我的網頁中運行:

FindMyLocation(function() { 
myPos = this; 
}); 

當我CONSOLE.LOG回調裏面myPos,我見價值。不過,我希望能夠在此回調之外使用myPos來進行距離計算。現在,它不會工作。

請幫忙。

+0

什麼問題? – David

+0

@David:當我嘗試提醒或console.log myPos(聲明爲全局)時,我得到未定義的值。有任何想法嗎?對於這個問題,我在回調和JavaScript方面不夠強大。 「 – Mina

+1

」'但是,我希望能夠在此回調之外使用myPos來進行距離計算。「爲什麼不在回調中計算距離?或者,如果您定期執行距離計算或響應某個事件,只需在計算之前測試是否定義了「myPos」(並且如果還沒有設置,則顯示一條消息,如「仍在獲取位置...」 )。 – apsillers

回答

0
    <script lang="JavaScript" type="text/javascript"> 
         $.post(window.baseUrl + 'includes/tagmap.php', 
           { name:"<?php echo $value->business_name; ?>", 
           x: "<?php echo $value->x; ?>", 
           y: "<?php echo $value->y; ?>", 
           action:"populate"}, function(data){ 
            var locdata = $.parseJSON(data);   
            function ShowMyLocation() { 
             FindMyLocation(function(myPos) { 
              myPos = this;                                  addMarker(locdata.x,locdata.y,locdata.name); 
             }) 
             FindMyLocation(); 
            } 
            ShowMyLocation();         
           });         
        </script>