0

存儲座標我創建的HTML按鈕:的Javascript地理定位:在陣列

​​

其中齒輪的stLoc()Javascript函數。

我的意圖是存儲vaulesX陣列內的緯度。

這裏是我的代碼:

var valuesX=[]; 

//This is to show the current position: 

function handleLoc(pos) { 
var a=pos.coords.latitude; 
var b=pos.coords.longitude; 
var p = new L.LatLng(+a, +b); 
mark(p); 
} 

//Here I intend to store the latitude using "valuesX.push": 

function stLoc(pos) { 
var a=pos.coords.latitude; 
var b=pos.coords.longitude; 
var p = new L.LatLng(+a, +b); 
mark(p); 
valuesX.push(a); 
} 

//And this is to enable the geolocation: 
function handleErr(pos) { 
document.write("could not determine location"); 
} 

if (navigator.geolocation) { 
navigator.geolocation.watchPosition(handleLoc,handleErr); 
} 
else { 
document.write("geolocation not supported"); 
} 

我得到的輸出是一個空數組。

+2

你怎麼居然通過'pos'到'stLoc(pos)'? – Grampa 2012-08-12 09:11:14

回答

0

您的stLoc()函數期望pos要作爲第一個參數傳遞的對象。

但在例如你的HTML部分你不通過這個參數功能:

<a "onclick="stLoc();">

這將導致錯誤和應用程序流斷裂。

更新:

<a href="#" onclick="return stLoc();">button</a> 

<script type="text/javascript"> 
var valuesX=[], 
    lastPos={a: -1, b: -1}; 
//This is to show the current position: 

function handleLoc(pos) { 
    // in event handler remember lastPos to use it in stLoc on click. 
    lastPos.a = pos.coords.latitude; 
    lastPos.b = pos.coords.longitude; 
    var p = new L.LatLng(lastPos.a, lastPos.b); 
    mark(p); 
} 

//Here I intend to store the latitude using "valuesX.push": 

function stLoc() { 
    if(lastPos.a != -1) { 
     valuesX.push(lastPos.a); 
    } 
    return false; 
} 

//And this is to enable the geolocation: 
function handleErr(pos) { 
    document.write("could not determine location"); 
} 

if(navigator.geolocation) { 
    navigator.geolocation.watchPosition(handleLoc,handleErr); 
} 
else { 
    document.write("geolocation not supported"); 
} 
</script> 
+0

我試過了,但是仍然得到一個空數組。 – multigoodverse 2012-08-12 11:02:57

+0

你可以添加console.log(pos);在var a = pos.coords.latitude之前;並在控制檯中讀取輸出?然後把console.log(a);之前valuesX.push(a);並閱讀輸出。在push()方法調用引發錯誤之前看起來有些代碼。 – 2012-08-12 11:10:04

0

對於男人找出來的代碼以不同的方式來實現這一功能.. 下面是代碼

<script language="javascript" src="http://code.jquery.com/jquery-1.6.2.min.js"></script> 
<script language="javascript"> 
function geoSuccess(e){ 
    var lat = e.coords.latitude; 
    var lon = e.coords.longitude; 
    var myLoc = "Latitude: " + lat + '<br />Longitude: ' + lon; 
    $("#mylocation").html(myLoc); 
} 
function geoFailed(e){ 
    $("#mylocation").html("Failed"); 
} 
window.onload=function(e){ 
    if (navigator.geolocation){ 
     navigator.geolocation.getCurrentPosition(geoSuccess, geoFailed); 
    } else { 
     // Error (Could not get location) 
     $("#mylocation").html("Failed"); 
    } 
} 
</script> 
<div id="mylocation"></div>