题记
最近在开发新功能时需要引入百度地图API,因为开始团队选用Ember.js
框架来开发,而在Ember.js
框架中使用地图的文档国内外都极少,所以特别在此记录总结一下
百度地图API
主要是初始化设置和API使用,官方文档已经很详尽就不多解释了
Ember.js
按照正常来讲,Ember.js
是支持原生js的,但是他的页面是通过Handlebars
输出,所以需要做一些特殊处理,在index.html
中
在main.js
文件中
App = Ember.Application.create();App.Router.map(function() { // put your routes here});App.IndexRoute = Ember.Route.extend({ model: function() { }});App.BaiduMapsComponent = Ember.Component.extend({ insertMap: function() { var map = new BMap.Map("allmap"); var point = new BMap.Point(121.462,31.256); var top_right_navigation = new BMap.NavigationControl({anchor: BMAP_ANCHOR_TOP_RIGHT}); map.centerAndZoom(point, 13); map.addControl(top_right_navigation); map.enableScrollWheelZoom(true); }.on('didInsertElement')});
高级实现
在上面的步骤中我们已经将地图API在Ember.js
框架中初始化了,但是我们现在需要添加一个select框使用ember select
,它能够自动从后端传来的json数据中获取长宁,黄埔,浦东三个name值,并且在选择黄埔后地图能够移到以黄埔区域为中心的地方,具体实现如下index.html
在main.js文件中
App = Ember.Application.create();App.Router.map(function() { // put your routes here});App.IndexRoute = Ember.Route.extend({ model: function() { return { locations: [ { name: '长宁', latitude: 121.427102, longitude: 31.225449 }, { name: '黄埔', latitude: 121.481144, longitude: 31.241073 }, { name: '浦东', latitude: 121.544816, longitude: 31.229834 } ] };}});App.BaiduMapsComponent = Ember.Component.extend({ insertMap: function() { var baimap = new BMap.Map("allmap"); baimap.centerAndZoom(new BMap.Point(this.get("latitude"),this.get("longitude")),15); this.set('map', baimap); }.on('didInsertElement'), coordinatesChanged: function() { var map = this.get('map'); if (map) map.setCenter(new BMap.Point(this.get('latitude'), this.get('longitude'))); }.observes('latitude', 'longitude')});
总结
在main.js
中coordinatesChanged
函数的主要作用是当select发生变化时,他能够将题图的Center设置所选的位置