4

backbone.js とリーフレットに基づいてアプリケーションを構築しようとしています。ユーザーは地図をドラッグして、地図上にマーカーを表示できました。マーカーは、クリックして選択できます。選択すると、アイコンと (ポップアップではない) に表示されるマーカーの詳細情報を変更する必要があります。

私のバックボーン モデルは、いくつかのエンティティで構成されています。

マーカー モデルには、緯度、経度の種類、タイトル、isSelected が含まれます

マップ モデルの内容: マップの中心、マーカー コレクション、選択したマーカー

この種の機能を作成する方法を知っている人はいますか? リーフレット マーカーをバックボーン ビューとして作成するにはどうすればよいですか?

4

1 に答える 1

2

バックボーンビューとリーフレットオブジェクトモデルは完全には適合しません。これは、マーカーがDOM要素内に含まれていないためです。これはBackbone.View.el、表現することになっているものです。もちろん、マーカーに要素(を介してアクセス可能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();
        });
    }
});

これがJSFiddleのデモです

于 2013-01-25T09:00:45.387 に答える