2013-02-26 80 views
-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> 

嗨,纠正错字后,脚本仍然没有工作。即没有显示经度和纬度。

+0

我的猜测没有例外的是,'navigator.gelocation'拼错了,应该是'navigator.geolocation'。 – 2013-02-26 13:17:34

+0

也正如本文解释,http://stackoverflow.com/questions/3397585/navigator-geolocation-getcurrentposition-sometimes-works-sometimes-doesnt,在getMyLocation()之前定义'displayLocation'函数。 – 2013-02-26 13:19:46

+0

嗨,纠正错字后,脚本仍然无法正常工作。即没有显示经度和纬度。 – user2106416 2013-02-26 13:44:08

回答

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> 
+0

它仍然无法正常工作。 :( – user2106416 2013-02-26 15:51:06

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>