2013-02-26 81 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>