我正在尝试学习使用javascript来使用地理位置。 但是,脚本不能像我想的那样工作。 以下是我的代码:
<!doctype html>
<html>
<title> Testing Geolocation</title>
<head>
<script>
function displayLocation(){
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var div = document.getElementById("myLocation");
div.innerHTML =" You are at Latitude "+latitude+" and longitude "+longitude);}
window.onload = getMyLocation;}
function getMyLocation{
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(displayLocation);}
else{
alert("Oops! Geolocation function not supported");}
</script>
</head>
<body>
<div id="myLocation">
Your location will go here.
</div>
</body>
</html>
嗨,在纠正错字后,脚本仍无法正常工作。即纬度和经度没有显示。
答案 0 :(得分:1)
将参数'position'添加到displayLocation函数。
UPD:..和一些错别字。您是否使用Chrome / FF控制台进行错误跟踪?试试这个:<script>
function displayLocation(position){
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var div = document.getElementById('myLocation');
div.innerHTML = "You are at Latitude "+latitude+" and longitude "+longitude;
}
function getMyLocation(){
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(displayLocation);
} else {
alert('Oops! Geolocation function not supported');
}
}
getMyLocation();
</script>
答案 1 :(得分:0)
您的getMyLocation
函数缺少(),该函数的最终}
(并且在window.onload行之后还有一个}
):
<!doctype html>
<html>
<title> Testing Geolocation</title>
<head>
<script>
function displayLocation(position){
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var div = document.getElementById("myLocation");
div.innerHTML =" You are at Latitude "+latitude+" and longitude "+longitude;}
function getMyLocation(){
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(displayLocation);}
else{
alert("Oops! Geolocation function not supported");}
}
window.onload = getMyLocation;
</script>
</head>
<body>
<div id="myLocation">
Your location will go here.
</div>
</body>
</html>