2013-02-05 57 views
1

我正在为HTML 5地理定位编写Java脚本,但它似乎不起作用,当我尝试在另一个作用域中输出内容时,它说未定义。以下是代码。只有当HTML页面托管在Web服务器上,而不是在本地主机HTML5地理定位问题

<script> 
var lat; 
var lng; 
function getLocation() 
    { 
    if (navigator.geolocation) 
    { 
    navigator.geolocation.getCurrentPosition(showPosition); 
    } 
    else{} 
    } 
function showPosition(position) 
    { 
    lat = position.coords.latitude; 
    lng = position.coords.longitude; 
    document.write(lat); // Doesnt output anything 
    } 


</script> 

    <script type="text/javascript"> 
      document.write(lat);  // It says undefined 
     $(document).ready(function() 
     { 
      //some scripts here 

     } 

</script> 
+0

这不是脚本错误,还有其他的东西,比如本地测试,或者你没有给予浏览器权限 – Toping

回答

0

成功回调函数被调用。你在本地测试还是在网络服务器上测试?

+1

仅仅通过Chrome浏览器,你可以从具有SSL,HTTPS或其他加密方法的交错/安全服务器追踪你的位置。请查看[Google产品论坛](http://productforfors.google.com/forum/#!msg/chrome/vhDaFt-pOfA/t1euklGluFkJ) – NielsInc

+0

@NielsInc,该问题不在托管或范围界定上,而在于异步性质java脚本。 document.write()为null的原因是因为document.write()在地理定位之前执行。我设法通过执行showPosition(position)函数里的函数来让程序工作 –

+0

Allright!对你好,你修好了!它只是在我尝试在本地主机上测试时得到的错误相同的症状,所以我想我会与你分享。 – NielsInc