2017-07-21 199 views
0

我正在做一本练习,出于某种原因,我无法让Geolocation API将我的坐标发回给我。浏览器提示我获取我的位置的权限,所以很多工作,但它不会更新div与“位置”ID中的文本。JavaScript:没有通过地理位置API获取位置

我想我通过document.getElementById函数正确访问元素。

HTML:

<!doctype html> 
<html> 
    <head> 
     <meta charset = "utf-8"> 
     <title>Where am I?</title> 
     <script src="loc.js"></script> 
     <link rel="stylesheet" href="loc.css"> 
    </head> 

    <body> 
     <div id="location"> 
      Your location will be here. 
     </div> 
    </body> 

</html> 

JS:

window.onload = getMyLocation; 

function getMyLocation(){ 
    if(navigator.geolocation){ 
     navigator.geolocation.getCurrentPosition(displayLocation); 
    } else { 
     alert("Ooops, no geolocation support!") 
    } 
} 

function displayLocation(position){ 
    var latitude = position.coords.latitude; 
    var longitude = position.coords.longitude; 

    var div = document.getElementById("location"); 
    div.innerHTML = "You are at Latitude: " + latitude + ", Longtitude: " + longitude; 
} 
+0

我刚刚运行你的代码,它的工作。你是否正确地从Google获取纬度/经度,只有显示不起作用? –

+0

我刚刚被提示授予权限(我这样做),但该页面不会从原始HTML更新。它只是说“你的位置会在这里。”如果你得到“你在Latitude:X,Longitude:Y”,那么我认为问题在我的最后,而不是代码。 – Matt

+0

在您的代码var var longitude放入alert(longitude)后;你应该得到一个数字。 –

回答

0

您必须在大多数浏览器使用HTTPS,这些天来访问地理位置。本地主机URL可能会或可能无法工作。