【问题标题】:Uncaught ReferenceError: lat is not defined [duplicate]未捕获的 ReferenceError:未定义纬度 [重复]
【发布时间】:2013-01-29 23:41:05
【问题描述】:

可能重复:
JavaScript Variable Scope

我的脚本有问题,我想从 pos 函数中获取值 lat,lng,但是当我在控制台中检查元素时,我得到了这个错误:

"Uncaught ReferenceError: lat is not defined TEST.html:30 (匿名函数)"

第 30 行是:var latlng = new google.maps.LatLng (lat, lng); 这是我的完整代码:

<script type="text/javascript">

navigator.geolocation.getCurrentPosition (function (pos){
  lat = pos.coords.latitude;
  lng = pos.coords.longitude;
});

  var directionsDisplay;
  var directionsService = new google.maps.DirectionsService();
  var map;
  var latlng = new google.maps.LatLng (lat, lng);
  var oceanBeach = new google.maps.LatLng(-6.2501199999999999,106.75937);

  function initialize() {
    directionsDisplay = new google.maps.DirectionsRenderer();
    var mapOptions = {
      zoom: 14,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      center: latlng
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    directionsDisplay.setMap(map);
  }

  function calcRoute() {
    var selectedMode = document.getElementById("mode").value;
    var request = {
        origin: latlng,
        destination: oceanBeach,
        // Note that Javascript allows us to access the constant
        // using square brackets and a string value as its
        // "property."
        travelMode: google.maps.TravelMode[selectedMode]
    };
    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
      }
    });
  }
</script>

【问题讨论】:

  • 如果这正是您使用的代码。问题是您的 lat 和 lng 变量是在与您尝试使用它们的上下文不同的上下文中声明的。
  • 将getCurrentPosition后面的代码移动到回调函数中。既然那是你的变量所在的地方,那么使用它们的代码应该在哪里难道没有意义吗?

标签: javascript geolocation


【解决方案1】:

您至少有两个问题:

  1. 变量的范围(它们在子函数中定义,在您尝试使用它们的范围内不可用)

  2. getCurrentPosition() 函数是异步的。这意味着它会在您调用它之后完成一段时间,并且仅在它调用完成回调函数时才完成。因此,在您尝试使用函数调用后的结果时,它还没有完成。

要处理 getCurrentPosition() 是异步的,您必须这样做:

navigator.geolocation.getCurrentPosition (function (pos){
    var lat = pos.coords.latitude;
    var lng = pos.coords.longitude;
    var latlng = new google.maps.LatLng (lat, lng);
    var oceanBeach = new google.maps.LatLng(37.7683909618184, -122.51089453697205);      
    // any further code that uses these variables
});

// no code here that uses the results of getCurrentPosition() 
// because it has not completed yet

你可以在这里看到类似的问题和答案:unable to cope with the asynchronous nature of navigator.geolocation

【讨论】:

  • 是的,你的代码运行良好,但我需要在另一个函数中调用 var。
  • @in-c - 然后你必须从你的完成函数中调用该函数并将这个变量传递给它。如果不改变编写代码的方式,就无法使用异步 API 进行顺序编程。这就是它们工作方式的本质。您将必须学习如何以这种方式编写代码以使用任何类型的异步 API。对于学习 javascript 和异步 API 的人来说,这是一个非常常见的绊脚石。解决它的唯一方法是学习编写代码所需的新方法。
【解决方案2】:

如果你这样写会不会有问题:

navigator.geolocation.getCurrentPosition (function (pos){
     var lat = pos.coords.latitude;
     var lng = pos.coords.longitude;
     var latlng = new google.maps.LatLng (lat, lng);
     var oceanBeach = new google.maps.LatLng(37.7683909618184, -122.51089453697205);
});

之所以大喊大叫,是因为 lat 与在回调函数之外定义的 latlng 和 oceanBeach 定义在不同的范围内,并且在那里无法访问它

更新

考虑到您的情况,您可以使用回调来解决您的问题,即将 getCurrentPosition 变成自己的函数,例如:

 function getCurrentLocation(callback) {
   if(navigator.geolocation) {
     navigator.geolocation.getCurrentPosition(function(pos) {
     var lat = pos.coords.latitude;
     var lng = pos.coords.longitude;
     callback(new google.maps.LatLng(lat,lng), new google.maps.LatLng(-6.2501199999999999,106.75937));
   });
  }
  else {
   throw new Error("Your browser does not support geolocation.");     
  }
} 

并为每个 ie 使用单独的回调调用它们

   getCurrentLocation(function(latlng,oceanBeach){
  // work with latlng and ocean beach here
  });

现在终于从每个函数调用函数,即

<script type="text/javascript">

var directionsDisplay;
var directionsService = new google.maps.DirectionsService();

function initialize() {
 getCurrentLocation(function(latlng,oceanBeach){
   directionsDisplay = new google.maps.DirectionsRenderer();
   var mapOptions = {
   zoom: 14,
   mapTypeId: google.maps.MapTypeId.ROADMAP,
   center: latlng
   }
   map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
   directionsDisplay.setMap(map);
 });

}

</script>

并为 calcRoute 使用相同的技术。注意:不要让方向显示和方向服务保持全局,你应该把整个东西变成一个类,这样它就更干净了,更面向对象

【讨论】:

  • 是的,你是真的,但我需要在另一个函数中调用它,我编辑并添加我的完整代码,请阅读,谢谢
  • 你需要重构你的代码,以便每个函数调用都可以使用 latlng。您可以将 navigator.geolocation.getCurrentPosition 制作成它自己的函数并从中获取每个函数的 latlng 值,或者在全局范围内保持 latlng [我不推荐]
  • 我也更新了我的答案来解决你的情况
  • 谢谢的地图正在显示,但我无法获得方向。
  • 对不起,你指的方向显示不可见?
猜你喜欢
  • 2012-09-07
  • 2012-03-03
  • 2016-08-10
  • 2023-03-04
  • 1970-01-01
  • 2014-06-17
  • 1970-01-01
  • 1970-01-01
  • 2015-07-11
相关资源
最近更新 更多