Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Google maps 为什么谷歌地图变量不可访问?_Google Maps_Coffeescript_Scope - Fatal编程技术网

Google maps 为什么谷歌地图变量不可访问?

Google maps 为什么谷歌地图变量不可访问?,google-maps,coffeescript,scope,Google Maps,Coffeescript,Scope,我的js文件中有以下代码 $(document).ready -> mapOptions = null map = null set_user_location = (position) -> mapOptions = center: new google.maps.LatLng(position.coords.latitude, position.coords.longitude) zoom: 14 console.log mapOp

我的js文件中有以下代码

$(document).ready ->
  mapOptions = null
  map = null
  set_user_location = (position) ->
    mapOptions =
      center: new google.maps.LatLng(position.coords.latitude, position.coords.longitude)
      zoom: 14
  console.log mapOptions
  map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions)
在控制台中查找mapOptions变量时,该变量的值为null。
我是不是漏掉了什么明显的东西?。请提供帮助。

如果您希望
地图
为全局地图,则必须手动将其附加到
窗口
(假设您在浏览器中):

或者像这样:

@map = null
$(document).ready ->
  #...
不过,您必须非常小心如何引用
map
,否则CoffeeScript会认为您需要一个局部变量;例如,这不会做您可能认为的事情:

@map = null
$(document).ready ->
  map = something
这将在回调函数中生成一个局部
map
变量,这样全局
map
就不会被触及

如果您想要一个全局名称空间,我建议您设置一个全局应用程序特定的名称空间:

# Somewhere before anything else happens...
@your_app_name = { }
$(document).ready ->
  your_app_name.map = null
  #...
然后将任何全局属性设置为命名空间中的属性:

# Somewhere before anything else happens...
@your_app_name = { }
$(document).ready ->
  your_app_name.map = null
  #...

现在,您必须始终包含完整的名称空间(这有助于避免命名冲突),而且您不必太担心CoffeeScript在需要局部变量和全局变量时会产生混淆。

if navigator.geolocation navigator.geolocation.getCurrentPosition(set\u user\u location,error)position是浏览器传递的变量,用于设置用户位置方法
getCurrentPosition
异步运行,在
set_user_location
中初始化地图,或者在
set_user_location
外部使用默认的-
center
初始化地图,并在
set_user_location
Hmm中分配一个新的
center
。我的观点是,我想使地图变为全局的,这样我的所有函数都可以访问它,因为我的应用程序很漂亮映射密集型..你能建议一种方法吗?我对coffeescript不是很有经验,但是如果你在全局范围内(在
$(文档)之外)声明map变量,它将是全局的。准备好了吗
)谢谢你的全面解释..帮助很大。