-1

我正在尝试学习使用 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>

您好,改正错字后,脚本仍然无法正常工作。即纬度和经度没有显示。

4

2 回答 2

1

将参数“位置”添加到您的 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>
于 2013-02-26T15:05:55.567 回答
0

您的getMyLocation函数缺少 () ,并且该函数缺少 final }(并且}在 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>
于 2013-02-26T15:59:10.340 回答