我正在尝试开发一个基于 Backbone JS 的应用程序。我想嵌入一个基于传单 JS 的 OpenStreetMap 地图,但我找不到任何教程。
问问题
3718 次
2 回答
8
我发现上面的答案错误地渲染了地图。
Leaflet 期望在初始化地图时包含元素已经位于 DOM 中。这就是为什么使用setTimeout
“作品”。到setTimeout
触发时,视图已附加到页面,因此 Leaflet 可以正确初始化。
我相信将附加步骤和渲染步骤分开会更干净。通过在呈现之前将视图附加到页面,您可以确保 Leaflet 将正确初始化而无需使用setTimeout
.
这是一个基于上述示例的示例:
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 © <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();
于 2013-02-23T01:50:56.983 回答
2
I've created a jsfiddle to show how you can use Leaflet inside a Backbone.View: 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 © <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/
于 2013-01-13T16:12:24.443 回答