未捕获的TypeError:无法设置undefined的属性“position”

时间:2011-12-13 00:48:53

标签: javascript google-maps google-maps-api-3 coffeescript

我有这段代码给我一些奇怪的错误信息

Uncaught TypeError: Cannot set property 'position' of undefined

这是一个jQuery插件的内部,用于在弹出窗口中显示谷歌地图。 我在其他地方使用代码,它工作正常 - 这里唯一的区别似乎是我现在在弹出窗口中使用它。我错过了范围问题吗? 像geocoderParams和latlng这样的所有变量都应该像它们那样填充。 谷歌搜索错误消息没有任何价值。

调用google.maps.Map()时会触发错误消息。

self = $(this)
self.hide()

geocoder = new google.maps.Geocoder
geocoderParams =
  address: self.data('address') || settings.address
  region: settings.region

results = geocoder.geocode geocoderParams, (results, status) ->

if status == google.maps.GeocoderStatus.OK
  latlng = results[0].geometry.location

  mapOptions =
    mapTypeControl: false
    overviewMapControl: false
    zoom: settings.zoomLevel
    center: latlng
    mapTypeId: google.maps.MapTypeId.ROADMAP

  map = new google.maps.Map(self, mapOptions)

self.show()

3 个答案:

答案 0 :(得分:66)

我查了google.maps.Map()Google reference说第一个参数应该是mapDiv:Node,它是地图的容器,通常是div元素。< / p>

您正在传递$(this),这可能是一个jQuery对象,而不是Google地图所期望的对象。我不知道你的其余代码,但也许你应该只是传递this而不是$(this)

答案 1 :(得分:31)

如果您正在使用jQuery,则需要传递vanilla HTMLElement(例如Node)而不是jQuery选择(例如Array / NodeList$()查询返回。

如果添加控制台命令:

console.log(self);

它会返回类似的内容:

[ ▶ <div id="map_canvas"></div> ]

从jQuery数组中获取值,替换:

map = new google.maps.Map(self, mapOptions)

使用:

map = new google.maps.Map(self[0], mapOptions)

答案 2 :(得分:20)

尝试使用以下内容启动地图时遇到此错误:

map = new google.maps.Map($('#map-canvas'), mapOptions);

我能够通过在选择器之后添加[0]来选择选择器返回的第一个(也是唯一的)项来解决它:

map = new google.maps.Map($('#map-canvas')[0], mapOptions);