2 google-maps-api-3 backbone.js
我有一个backbone.js模型.我想从该模型的方法加载谷歌地图API javascript.我不想在文档的头部加载脚本.
我可以使用$ .getScript()来加载js然后显示地图?但是当我指定回调函数 http://maps.googleapis.com/maps/api/js?key=API_KEY&sensor=TRUE&callback=initialize时
我总是得到一个错误,因为我不想定义一个全局的js函数initialize().我希望回调方法是一个相同的backbone.js模型的方法.
App = Backbone.Model.extend({
construct : function(),
displayMap : function()
{
$.getScript("http://maps.googleapis.com/maps/api/js?key=API_KEY&sensor=TRU&callback=initialize", function(data, textStatus, jqxhr) {
console.log('Load was performed.');
});
},
initialize: function()
{
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
}
Run Code Online (Sandbox Code Playgroud)
});
var App = new App();
App.displayMap();
Run Code Online (Sandbox Code Playgroud)
尝试使用此结构的地图模型:
Map = Backbone.Model.extend({
defaults: {
id: '', currentLatLng: {}, mapOptions: {}, map: {},
position: {}, zoom: 13, maxZoom: 16, minZoom: 12
},
initMap: function(position){
this.set('position', position);
var currentLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
this.set('currentLatLng', currentLatLng);
var mapOptions = {
zoom: this.get('zoom'),
minZoom: this.get('minZoom'),
maxZoom: this.get('maxZoom'),
center: currentLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};
this.set('mapOptions', mapOptions);
}
});
Run Code Online (Sandbox Code Playgroud)
此视图代码:
MapView = Backbone.View.extend({
defaults:{
region: 'us', language: 'en'
},
id: 'gmaps-container',
className: 'gmaps_container',
initialize: function(){
var url = "http://maps.googleapis.com/maps/api/js?key=key_here&sensor=false";
$.ajax({
url: url,
dataType: "script",
async: false,
success: function(){
console.log('script loaded');
}
});
this.model.set('map', new google.maps.Map(this.el, this.model.get('mapOptions')));
},
render: function(){
console.log('init map');
$('#' + this.id).replaceWith(this.el);
return this;
}
});
Run Code Online (Sandbox Code Playgroud)
只需在主脚本中初始化模型和视图:
var map = new Map({zoom: 8, maxZoom: 18, minZoom: 8});
map.initMap({coords: {latitude: -34.397, longitude: 150.644}});
var mapView = new MapView({model: map});
mapView.render();
Run Code Online (Sandbox Code Playgroud)
你还需要简单的html容器:
<div id="gmaps-container" class="gmaps_container"></div>
Run Code Online (Sandbox Code Playgroud)
注意:设置容器的宽度和高度.