谷歌地图 – 未捕获的TypeError:无法设置未定义的属性“位置”

我使用backbone.js作为我的框架。 我的问题是,当我尝试将google地图与backbone.js集成时,我遇到了这个奇怪的问题。

Uncaught TypeError: Cannot set property 'position' of undefined 

该教程来自该站点。

https://developers.google.com/maps/documentation/javascript/examples/event-closure

即使我已经尝试过这些解决方案,问题仍然存在。

  • 未捕获的TypeError:无法设置undefined的属性“position”
  • 谷歌地图请求返回“无法设置未定义的属性’位置”

我的代码如下

JS

 define(['jquery', 'underscore', 'backbone', 'text!modules/map/mapListViewTemplate.html'], function($, _, Backbone, mapListViewTemplate) { var MapListView = Backbone.View.extend({ initialize: function() {}, render: function() { var mapOptions = { zoom: 4, center: new google.maps.LatLng(-25.363882, 131.044922) }; var map = new google.maps.Map($('#map-canvas'), mapOptions); // Add 5 markers to the map at random locations var southWest = new google.maps.LatLng(-31.203405, 125.244141); var northEast = new google.maps.LatLng(-25.363882, 131.044922); var bounds = new google.maps.LatLngBounds(southWest, northEast); map.fitBounds(bounds); var lngSpan = northEast.lng() - southWest.lng(); var latSpan = northEast.lat() - southWest.lat(); for (var i = 0; i < 5; i++) { var position = new google.maps.LatLng( southWest.lat() + latSpan * Math.random(), southWest.lng() + lngSpan * Math.random()); var marker = new google.maps.Marker({ position: position, map: map }); marker.setTitle((i + 1).toString()); this.attachSecretMessage(marker, i); } this.$el.html(mapListViewTemplate); }, attachSecretMessage: function(marker,num) { var message = ['This', 'is', 'the', 'secret', 'message']; var infowindow = new google.maps.InfoWindow({ content: message[num] }); google.maps.event.addListener(marker, 'click', function() { infowindow.open(marker.get('map'), marker); }); }, remove: function() { Backbone.View.prototype.remove.call(this); $(window).off('scroll'); } }); return MapListView; }); 

HTML

 

谢谢。

你必须换行

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

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

Map()构造函数期望Node对象。 另见jQuery get DOM节点? 以及如何从JQuery选择器获取DOM元素

更新:如果map container div元素的id是maplist-page不是use:

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

另请参见没有backbone.js的jsbin示例 。

问题是我猜测在初始化地图时还没有渲染div。 所以, this.$el.html(mapListViewTemplate); 应该是render方法中的第一行。

然后使用dom元素初始化Google Maps,而不是像Anto Jurkovic所说的jQuery对象: var map = new google.maps.Map($('#map-canvas')[0], mapOptions);