繁体   English   中英

Javascript地理位置:将坐标存储在数组中

[英]Javascript Geolocation: Storing coordinates in an array

我创建了一个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");
}

我得到的输出是一个空数组。

您的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>

对于那些寻找以不同方式实现此功能的代码的人。这是代码

<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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM