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

Javascript Geolocation: Storing coordinates in an array

本文关键字:数组 存储 坐标 地理位置 Javascript      更新时间:2023-09-26

我创建了一个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>