【问题标题】:Leaflet markers from Backbone.js collection?Backbone.js 集合中的传单标记?
【发布时间】:2013-01-08 16:57:15
【问题描述】:

我正在尝试构建一个基于backbone.js 和传单的应用程序。 用户可以拖动地图并查看地图上的标记。 可以通过单击来选择标记。选择后,他们必须更改其图标和显示在(非弹出窗口)上的标记详细信息。

我的主干模型由几个实体组成:

标记模型包含 纬度,经度 类型, 标题, 被选中

地图模型包含: 地图中心, 标记集合, 选定的标记

任何人都知道我怎样才能实现这种功能? 如何将传单标记作为主干视图?

【问题讨论】:

    标签: backbone.js leaflet


    【解决方案1】:

    主干视图和传单对象模型并不完美,因为标记不包含在 DOM 元素中,而这正是 Backbone.View.el 应该表示的内容。标记确实当然有一个元素(可通过marker._icon 访问),但在标记渲染到地图之前它不存在。

    也就是说,您可以用 Backbone 视图表示标记,只是不能使用 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();
            });
        }
    });
    

    Here's a demo on JSFiddle.

    【讨论】:

    • JSFiddle 目前可能已经关闭。为什么选择 OpenLayers 而不是 Leaflet?根据您的回答,我猜目前没有像 Backbone.js 那样有点面向 MVC 的地图 API
    • @LaurynasMališauskas,通常是这样,但它会反弹。没有什么比我发布的更多了,只是一个使用这些视图的演示。
    • @LaurynasMališauskas 我使用了 OpenLayers,因为我的要求比 Leaflet 所能提供的要复杂一些。 Leaflet 是轻量级的,非常适合简单的地图和功能,但对于某些类型的应用程序,它只是不能削减它。如果我只需要渲染图块地图服务和标记,我也会使用 Leaflet。
    • 我必须在 App.Views.MapView 中将 id:"#map" 更改为 id:"map" 才能让您的 jsfiddle 正常工作。这是我的叉子:jsfiddle.net/dPqQy 感谢您的示例代码!
    猜你喜欢
    • 1970-01-01
    • 2012-05-10
    • 1970-01-01
    • 2012-10-30
    • 1970-01-01
    • 2011-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多