Java脚本当前地理位置
java script current geolocation
我需要在我的web应用程序中找到我自己。我使用谷歌地图来固定我的位置。我的问题是函数返回我的当前位置:
function setLocation() {
var temp = { lat: 0, lng: 0 };
navigator.geolocation.getCurrentPosition(function (position, temp) {
//here is all ok, temp.lat and tem.lng are assigned correctly
temp.lat = position.coords.latitude;
temp.lng = position.coords.longitude;
});
//here temp.lat and temp.lng are again 0
return temp;
}
我在代码中添加了一些注释来描述问题。我做错了什么?谢谢你的阅读。注:我是java脚本新手。
问题是你正在使用异步函数
返回值不正确,因为getCurrentPosition()尚未执行。您必须使用回调函数,该函数将在getCurrentPosition()完成后传递结果。正如Mike C所说,异步函数的更详细描述可以在如何从异步调用返回响应中找到?
function setLocation(callback)
{
var temp = {
lat: 0,
lng: 0
};
navigator.geolocation.getCurrentPosition(function (position, temp)
{
temp.lat = position.coords.latitude;
temp.lng = position.coords.longitude;
if ("function" === typeof callback)
{
callback(temp);
}
});
return;
}
setLocation(function (coords)
{
// This will alert the correct data
alert(coords.lat + " " + coords.lng);
});
承诺是一个更好的解决方案
回调会很快失控,所以我建议使用Promise对象。教程在https://davidwalsh.name/promises。其主要思想是,在使用异步任务时,您可以拥有易于阅读/理解的代码流。您的代码的一个例子是。
function setLocation()
{
return new Promise(function (resolve)
{
var temp = {
lat: 0,
lng: 0
};
navigator.geolocation.getCurrentPosition(function (position, temp)
{
temp.lat = position.coords.latitude;
temp.lng = position.coords.longitude;
resolve(temp);
});
return;
});
}
setLocation
.then(function (coords)
{
// This will alert the correct data
alert(coords.lat + " " + coords.lng);
});
相关文章:
- 安卓平台上的QWebView HTML5地理位置
- Possibile使用Manifest v2下的HTML5地理位置API将lat/long转换为国家/地区
- 如何在javascript清单中获取地理位置权限
- 地理位置和计算从当前纬度/液化天然气到另一纬度/液化石油气的距离
- 询问用户是否要打开地理位置
- 使用html5地理位置api创建地理围栏
- javascript显示地理位置
- 在地图加载/页面加载时,我想将地图设置为当前地理位置,但不想在地图上显示定位图标
- 为大型地理位置的坐标生成浮点数
- 根据客户的地理位置、邮政编码和位置切换图像
- HTML5地理位置,询问位置
- 谷歌地图/GMAP3 - 绘制从用户地理位置到已知目的地的路线 - 需要帮助
- 移动浏览器、地理位置和自动填充地址
- j查询地理位置和地图突出显示
- Javascript 地理位置:将坐标存储在数组中
- 无法使地理位置脚本工作
- 地理位置脚本不起作用
- 隐藏的“纬度”和“lng”字段没有被删除,所以我的脚本仍在从不正确的地理位置中搜索纬度和液化天然气结果
- Java脚本当前地理位置
- javascript地理位置不工作,除非我包括警报显示/延迟脚本