繁体   English   中英

Javascript:全局变量中的地理位置值

[英]Javascript: Geolocation values in global variable

我正在研究一个使用GPS的小型网络应用程序。 它使用Javascript完成此任务。 我在做什么:

  • 用两个空索引(纬度/经度)定义一个全局数组“ positionCoords”。
  • 准备好文档后,我正在使用功能“ getGeoLocation()”请求纬度/经度。
  • 请求后,我正在对数组进行简单的console.log。 数组索引仍然为空。
  • 在Webbrowser控制台中执行console.log(positionCoords),可以为我提供正确的值。

这可能与异步有关吗? 我对这个功能还很陌生,任何帮助将不胜感激!

// global variables
var positionCoords = {};
positionCoords['latitude'] = null;
positionCoords['longitude'] = null;

/*
 on document ready, excecute
  */
$(document).ready(function() {
    getGeolocation();
    console.log(positionCoords);
});

/*
 check if geolocation is supported and allowed, get coordinates
 */
function getGeolocation() {
    if (navigator.geolocation) {
        // geolocation is available
        navigator.geolocation.getCurrentPosition(
            function(position) {
                // get coordinates
                positionCoords['latitude'] = position.coords.latitude;
                positionCoords['longitude'] = position.coords.longitude;
                return true;
            },
            function(error){
                handleGeolocationErrors(error);
                return false;
            }
        );
    } else {
        // geolocation is not available
        console.log("Browser does not support geolocation services.");
        return false;
    }
}

在此处输入图片说明

使用Google Map进行演示

由于它是ASYNC调用,因此您需要将function-callback传递给getGeolocation ,然后将像follwong一样调用它:

通话中:

$(document).ready(function() {
    getGeolocation(function(coords){
          console.log(coords); 
           //====The resof your code which dependent on `coords` SHALL be here
           //......

   },function(err){console.log(err)});

});

为了能够像上面那样调用它,您需要通过传递两个参数来修改getGeolocation的实现:

  1. 函数回调onSuccess
  2. 函数回调onError

实现方式:

/*
 check if geolocation is supported and allowed, get coordinates
 */
function getGeolocation(fnsuccess,fnerror) {
    if (navigator.geolocation) {
        // geolocation is available
        navigator.geolocation.getCurrentPosition(
            function(position) {
               if(typeof fnsuccess==='function'){
                        fnsuccess.call(null,position.coords); //--Call CallBack On Success
                }
            },
            function(error){
                if(typeof fnerror ==='function'){
                      fnerror.call(null,error); //--Call CallBack On Error
                }
            }
        );
    } else {
        // geolocation is not available
        console.log("Browser does not support geolocation services.");
        return false;

    }
}

演示

DEMO会要求您分享您的位置,如果您接受,请检查浏览器的控制台,您将按预期获得Coords

使用Google Map进行演示

暂无
暂无

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

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