我正在尝试建立一个基于backbone.js和leaflet的应用程序。用户可以拖动地图并查看地图上的标记。可以通过单击标记来选择它们。当他们被选中时,他们必须改变他们的图标和标记的详细信息显示在一个(而不是弹出)。
我的主干模型由几个实体组成:
标记模型包含纬度、经度类型、标题、isSelected
地图模型包含:地图中心、标记集合、选定标记
有没有人知道我是怎么实现这种功能的?如何将传单标记作为主干视图?
发布于 2013-01-25 17:00:45
主干视图和leaflet对象模型并不完美匹配,因为标记不包含在DOM元素中,而DOM元素正是Backbone.View.el应该表示的元素。Markers do当然有一个元素(可通过marker._icon访问),但它在标记渲染到地图之前是不存在的。
也就是说,你的可以用主干视图表示标记,但你不能使用events或任何el相关的功能。我已经用OpenLayers成功地实现了类似的视图,它有同样的“问题”,而且工作得很好。
我认为这是最容易用代码来解释的:
//MarkerView has no element
App.Views.MarkerView = Backbone.View.extend({
initialize: function(options) {
//pass map instance to the marker
this.map = options.map;
//create the marker object
this.marker = L.marker([this.model.get('longitude'), this.model.get('latitude')]);
},
render: function() {
//append marker to the map
this.marker.addTo(this.map);
//can't use events hash, because the events are bound
//to the marker, not the element. It would be possible
//to set the view's element to this.marker._icon after
//adding it to the map, but it's a bit hacky.
this.marker.on('click', this.onClick);
},
onClick: function() {
alert("click");
}
});
//MapView renders a map to the #map element
App.Views.MapView = Backbone.View.extend({
id:"#map",
render: function() {
//render map element
var map = this.map = L.map(this.$el.attr('id'))
.setView([this.model.get('centerLon'), this.model.get('centerLat') ], 13)
.addLayer(L.tileLayer(this.model.get('layerUrl'), { maxZoom: 18 }));
//render each marker
this.markerViews = this.model.get('markers').map(function(marker) {
return new App.Views.MarkerView({model:marker, map:map}).render();
});
}
});https://stackoverflow.com/questions/14509770
复制相似问题