2012-08-10 75 views
0

我正在寻找一种方法来触发用户地理位置导航功能从另一个功能mapInit()。它几乎可以工作,但我不能有一个适当的回调getCurrentPosition(),以确认它进展顺利..它每次都返回undefined。地理位置无法返回确认?

我的地理定位对象将不得不实现其他任务,所以我不希望它触发mapInit()。它应该得到用户位置,记录它并返回truefalse ..任何猜测?

谢谢:)

// Get user current position, return true or false 
// 
var geolocation = { 
    get: function() { 
     if (alert(navigator.geolocation.getCurrentPosition(this.success, this.error, { 
      enableHighAccuracy: true, 
      maximumAge: 5000 
     })) { 
      return true; 
     } else { 
      return false; 
     } 
    }, 
    success: function(position) { 
     this.last = position; // record last position 
     return true; 
    }, 
    error: function() { 
     alert('code: ' + error.code + 'n' + 'message: ' + error.message + 'n') 
     return false; 
    }, 
    last: undefined, 
} 

// Initialize leaflet map and get user location if coords are undefined 
// 
var mapInit = function(latitude, longitude) { 
    if (!latitude && !longitude) { // if no latlng is specified, try to get user coords 
     if (geolocation.get()) { 
      latitude = geolocation.last.coords.latitude; 
      longitude = geolocation.last.coords.longitude; 
     } else { 
      alert('oups!'); 
     } 
    } 
    var map = L.map('map').setView([latitude, longitude], 15); 
    L.tileLayer('http://{s}.tile.cloudmade.com/#APIKEY#/68183/256/{z}/{x}/{y}.png', { 
     minZoom: 13, 
     maxZoom: 16, 
    }).addTo(map); 
    var marker = L.marker([latitude, longitude]).addTo(map); 
} 
+0

'getCurrentPosition()'似乎会返回,然后像W3C在API规范中写的那样异步获取用户位置:“调用时,它必须立即返回,然后异步地尝试获取设备的当前位置。 [(源)](http://dev.w3.org/geo/api/spec-source.html#geolocation)。有人有线索吗? – Antoine 2012-08-10 12:10:26

回答

1

不知道我理解你想要做什么,但是当你调用“getCurrentPosition”你通过了第一个参数是将与位置被调用一次它是方法检索。当您在您的评论说,getCurrentPosition总是立即返回,但回调方法将被调用,如果用户位置可被检索(它可能永远不会被调用):

navigator.geolocation.getCurrentPosition(function(position) { 
    var lat = position.coords.latitude; 
    var lon = position.coords.longitude; 
    //do something like recent the Map 
}); 

您需要首先创建单张地图一些默认坐标,然后使用提供给回调方法的坐标重新映射地图。

相关问题