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>
相关文章:
- 将数组存储到本地存储中,而不是替换
- 如何将数组存储
- 在 laravel 4 上使用循环将数据数组存储到单个数组中
- 将对象/数组存储在 jQuery Cookie 中
- 想要将数组存储为 JavaScript 映射中的值
- 在 mysql 中使用多维数组存储 $_POST
- 将php多维数组存储在localstorage中
- 将数组存储在jQuery cookie中
- 如何将php数组存储在一个cookie中,然后通过javascript读取它
- 如何用单引号将数组存储在javascript中?有可能吗
- 将数组存储在html数据属性中
- 使用javascript将数组存储为json中的密钥对
- 将数组存储在函数内部与存储在对象内部有什么好处吗
- 试图使用javascript将Object.keys(obj)的返回数组存储在数组中,但得到错误“ReferenceEr
- 在javascript中使用数组存储一组具有固定值的变量
- 如何在localStorage (Javascript)中使用数组存储JSON
- 数组存储javascript
- 我如何从数组存储访问JS函数
- 关于如何使用数组存储其他变量名称的任何想法
- 在chartJs中使用动态数组存储标签和数据