如何将此JavaScript代码的经度和纬度作为全局使用的变量。我已经尝试了几次但没有工作。
navigator.geolocation.getCurrentPosition(handle_geolocation_query,handle_errors);
function handle_errors(error)
{
switch(error.code)
{
case error.PERMISSION_DENIED: alert("user did not share geolocation data");
break;
case error.POSITION_UNAVAILABLE: alert("could not detect current position");
break;
case error.TIMEOUT: alert("retrieving position timed out");
break;
default: alert("unknown error");
break;
}
}
function handle_geolocation_query(position){
}
我在Jquery Mobile和PhoneGap应用程序中使用它。非常感谢任何帮助,谢谢
根据迄今为止给出的答案
$(document).ready(function(){
var latitude, longitude;
navigator.geolocation.getCurrentPosition(handle_geolocation_query,handle_errors);
function handle_errors(error)
{
switch(error.code)
{
case error.PERMISSION_DENIED: alert("user did not share geolocation data");
break;
case error.POSITION_UNAVAILABLE: alert("could not detect current position");
break;
case error.TIMEOUT: alert("retrieving position timed out");
break;
default: alert("unknown error");
break;
}
}
function handle_geolocation_query(position){
latitude = (position.coords.latitude);
longitude = (position.coords.longitude);
}
alert(latitude, longitude);
});
当我发出警报时,它会返回“未定义”
这是html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/gas-script.js"></script>
</head>
<body>
</body>
</html>
答案 0 :(得分:3)
在navigator.geolocation.getCurrentPosition:
之前var latitude, longitude;
在handle_geolocoation_query(position)里面:
latitude = position.coords.latitude;
longitude = position.coords.longitude;
使:
var latitude, longitude;
$(document).ready(function(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(handle_geolocation_query,handle_errors);
} else {
alert('Device probably not ready.');
}
});
function handle_errors(error) {
// error handling here
}
function handle_geolocation_query(position){
latitude = (position.coords.latitude);
longitude = (position.coords.longitude);
onPositionReady();
}
function onPositionReady() {
alert(latitude, longitude);
// proceed
}
答案 1 :(得分:0)
在下面提到的代码中,lat,lng应该在当前文件中全局可用,
$(document).ready(function(){
var lat, lng;
navigator.geolocation.getCurrentPosition(handle_geolocation_query,handle_errors);
function handle_geolocation_query(position){
lat = position.coords.latitude;
lng = position.coords.longitude;
}
});