在EmberJS框架中引用百度地圖API

題記

最近在開發新功能時須要引入百度地圖API,由於開始團隊選用Ember.js框架來開發,而在Ember.js框架中使用地圖的文檔國內外都極少,因此特別在此記錄總結一下html

百度地圖API

主要是初始化設置和API使用,官方文檔已經很詳盡就很少解釋了git

Ember.js

按照正常來說,Ember.js是支持原生js的,可是他的頁面是經過Handlebars輸出,因此須要作一些特殊處理,在index.htmljson

<script type="text/x-handlebars">
    {{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="index">
      {{baidu-maps}}
</script>
<script type="text/x-handlebars" id="components/baidu-maps">
    <div id="allmap"></div>
</script>

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框架

<script type="text/x-handlebars">

    {{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="index">
  {{view Ember.Select content=locations value=selectedLocation optionLabelPath="content.name"}}

  {{#if selectedLocation}}
      {{baidu-maps latitude=selectedLocation.latitude longitude=selectedLocation.longitude}}
  {{/if}}

</script>
<script type="text/x-handlebars" id="components/baidu-maps">
    <div id="allmap"></div>
</script>

在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.jscoordinatesChanged函數的主要做用是當select發生變化時,他可以將題圖的Center設置所選的位置this

相關文章
相關標籤/搜索