Javascript Geolocation:在数组中存储坐标

时间:2012-08-12 09:04:26

标签: javascript geolocation coordinates latitude-longitude navigator

我创建了一个HTML按钮:

...onclick="stLoc();"/>

它改变了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 个答案:

答案 0 :(得分: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>

答案 1 :(得分: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>