HTML5地理定位将当前GPS位置的长宽坐标转换为一个变量
HTML5 geolocation lat and long coordinates of current GPS position into a variable
我试图通过利用HTML5的地理定位功能获得用户当前的纬度和经度值。在研究并试图从StackOverflow上的其他问题中得到答案之后,我似乎仍然误解了访问全局变量的概念。到目前为止,我所看到的一切都表明瞄准镜有问题。我使用的代码看起来像是在使用函数中的函数。我目前正在运行以下代码:
<script type="text/javascript">
var currentLat = 0;
var currentLong = 0;
function getPosition() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
}
}
function showPosition(position) {
console.log(position.coords.latitude);
console.log(position.coords.longitude);
}
getPosition();
此代码当前的工作原理是将信息记录到控制台。但是,如果我将代码更改为此,它似乎不起作用:
<script type="text/javascript">
var currentLat = 0;
var currentLong = 0;
function getPosition() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
}
}
function showPosition(position) {
currentLat = position.coords.latitude;
currentLong = position.coords.longitude;
}
getPosition();
console.log(currentLat + "," + currentLong);
返回0就像我最初设置的那样。我已经搜索了很多关于全局变量,但大多数在线资源(包括StackOverflow)状态,我可以访问这些变量,只要我不重新声明函数内的变量(或创建覆盖全局变量的局部作用域变量)。
感谢gro的评论,我发现这是有效的:
window.onload = function(){
navigator.geolocation.getCurrentPosition(function(position) {
window.currentLat = position.coords.latitude;
window.currentLong = position.coords.longitude;
window.currentLatLong = new google.maps.LatLng(currentLat,currentLong);
init();
});
}
function init() {
// run code here and reference currentLatLong, currentLat and currentLong
}
相关文章:
- 将文本区域行/列转换为屏幕 x/y 坐标
- 如何使用谷歌地理编码将地址转换为坐标后控制台日志数据
- 使用openstreetmapapi转换城市中的坐标
- 将event.offsetX和event.offset Y的坐标转换为webGL本机坐标
- 如何使用JMapProjLib、Proj4j或Proj4js在不同坐标系之间转换坐标
- 画布 - 在调整窗口大小时转换鼠标坐标
- 如何将矩阵信息转换为简单的 x 和 y 坐标
- 如何将整数数组转换为人力车的 x/y 坐标
- OpenLayers:自动将 EPSG 4326 - 文本图层的坐标转换为地图的投影 (EPSG:900913)
- 将球体上的 3d 点转换为 UV 坐标
- 将 GPS 坐标转换为距离,并以十进制度为单位将距离转换为半径
- 将 GeoJSON 坐标转换为其他投影以用于草坪.js
- 将位置坐标转换为画布坐标
- 将街道地址转换为坐标并在 html 中放置
- 将局部(视口相对坐标)转换为全局(图层坐标)
- 如何将像素坐标转换为等轴测网格坐标
- 将纬度/纬度转换为像素坐标
- 如何将矢量(X,Y)位置转换为纬度/经度坐标?Javascript
- 将图像像素数据转换为坐标数组
- Pixi.js / WebGL方法,用于将数据模型坐标转换为画布像素坐标