让我给你一些关于这个项目的信息。我的项目的目标是编写一个应用程序,找到最接近用户的火车站(使用HTML5地理定位)。
问题是:我在屏幕上打印位置的功能不会等待地理位置在sessionStorage中。我知道这必须通过回调解决,但我无法弄清楚如何......
以下是相关代码:
window.onload = function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert("Geolocation werkt niet bij jou, sorry.");
}
}
function showPosition(position)
{
sessionStorage.setItem("userLat", position.coords.latitude);
sessionStorage.setItem("userLong", position.coords.longitude);
}
function cb(data)
{
var uLat = sessionStorage.getItem("userLat");
var uLong = sessionStorage.getItem("userLong");
var gegevens = data.Stations;
var result = Number.MAX_VALUE;
var nearIndex;
for (var i = 0; i < gegevens.length; i++)
{
var prev = haversine(uLat,gegevens[i].latitude,uLong,gegevens[i].longitude);
if (prev < result)
{
result = prev;
nearIndex = i;
}
}
var x = document.getElementById("dbStation");
x.innerHTML = "Je dichtsbijzijnde station is : " + gegevens[nearIndex].name;
}
通过以下代码从外部JSON文件导入数据:
<script type="text/javascript" src="http://data.irail.be/NMBS/Stations.json?callback=cb"></script>
答案 0 :(得分:0)
一种方法是在回调之前调用将位置设置为sessionStorage的函数,例如:
function setSessionStorage() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
return true;
} else {
alert("Geolocation werkt niet bij jou, sorry.");
return false;
}
}
//add the script
var oHead = document.getElementById('add');
var oScript = document.createElement('script');
oScript.type = 'text/javascript';
oScript.src = 'http://data.irail.be/NMBS/Stations.json?callback=cb';
oHead.appendChild(oScript);
oScript.onreadystatechange = function() {
if (this.readyState == 'complete') {
if( setSessionStorage() ) {
cb(); //your callback
}
}
}