简体   繁体   English

如何将js传单与Backbone js集成?

[英]How to integrate js leaflet with Backbone js?

I am trying to develop an application that is based on Backbone JS. 我正在尝试开发基于Backbone JS的应用程序。 I want to embed a OpenStreetMap map based on leaflet JS but I could not find any tutorial. 我想嵌入基于传单JS的OpenStreetMap地图,但找不到任何教程。

I found the above answer to render the map incorrectly. 我找到了以上答案,无法正确渲染地图。

Leaflet expects the containing element to already be located in the DOM when a map is initialized. Leaflet期望在初始化地图时包含元素已经位于DOM中。 This is why using setTimeout "works". 这就是为什么使用setTimeout “有效”的原因。 By the time setTimeout fires the View has been appended to the page, so Leaflet can initialize correctly. setTimeout触发时,View已添加到页面,因此Leaflet可以正确初始化。

I believe it is cleaner to break apart the append step and the render step. 我相信将附加步骤和渲染步骤分开是比较干净的。 By appending the View to the page before rendering it you can ensure that Leaflet will properly initialize without having to use setTimeout . 通过在视图呈现之前将视图附加到页面上,可以确保Leaflet可以正确初始化,而不必使用setTimeout

Here is an example, based on the one above: 这是一个基于上述示例的示例:

var MapView = Backbone.View.extend({

  render: function () {
    this.map = L.map(this.el).setView([55.75, 37.58], 10);

    L.tileLayer('http://{s}.tile.cloudmade.com/4e5f745e28654b7eb26aab577eed79ee/997/256/{z}/{x}/{y}.png', {
      attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://cloudmade.com">CloudMade</a>[…]',
      maxZoom: 18
    }).addTo(map);

    return this;
  }

});

$('body').append(MapView.el);
MapView.render();

I've created a jsfiddle to show how you can use Leaflet inside a Backbone.View: http://jsfiddle.net/theotheo/CJcK6/ 我创建了一个jsfiddle来展示如何在Backbone内部使用Leaflet。查看: http : //jsfiddle.net/theotheo/CJcK6/

// bare template
<script type='template' id='map-template'>
   <div id="map"></div>
</script>

// simple view
var MapView = Backbone.View.extend({
  template: _.template($('#map-template').html()),
  render: function () {
    this.$el.html(this.template());

    var map = L.map(this.$('#map')[0]).setView([55.75, 37.58], 10);
    L.tileLayer('http://{s}.tile.cloudmade.com/4e5f745e28654b7eb26aab577eed79ee/997/256/{z}/{x}/{y}.png', {
      attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://cloudmade.com">CloudMade</a>[…]',
      maxZoom: 18
    }).addTo(map);

    return this;
  }
});

Feel free to ask. 随便问。

Update : 更新

Example with jQuery Mobile: http://jsfiddle.net/theotheo/mh6mA/ jQuery Mobile的示例: http : //jsfiddle.net/theotheo/mh6mA/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM