HTML5地理定位将当前GPS位置的长宽坐标转换为一个变量

HTML5 geolocation lat and long coordinates of current GPS position into a variable

本文关键字:转换 坐标 变量 一个 定位 位置 GPS HTML5      更新时间:2023-09-26

我试图通过利用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
}