与Emberjs的GoogleMaps API

时间:2015-08-19 10:13:31

标签: javascript google-maps ember.js coffeescript emblem.js

我有一个带有EmberJs视图的GoogleMap。除数据绑定外,一切都很好。

我想将地图标记与ember-data绑定。如果某些内容在数据级别发生变化,则必须反映在Map上。

我尝试使用观察者,并重新运行makeMarkers方法来设置标记,但这似乎是一个糟糕的解决方案。

将数据与GoogleMaps绑定的最佳方式是什么?

2 个答案:

答案 0 :(得分:2)

在Ember 2.0上不推荐使用View,它们将在Ember 2.5中删除,制作如下组件:{{g-map markers = models}}

此组件包含一系列项目,此处为markers 你可以实现这样的东西:

import Ember from 'ember';
import MarkerSync from '../mixin/marker-synchronizer';

/**
 * Basic Component to display a google map,
 * Service & Marker have to be improved
 **/
export default Ember.Component.extend(MarkerSync, {
    classNames: 'google-map',
    googleMap: Ember.inject.service(),
    map: null,

    mapOptions: function () {
        return {
            center: new google.maps.LatLng(-34.397, 150.644),
            zoom: 8
        };
    },

    didInsertElement: function () {
        this.$().height('100%');
        this.$().width('100%');
        this.displayGmap();
        jQuery(window).on('resize', Ember.run.bind(this, this.handleResize));
    },

    willInsertElement: function () {
        this.get('googleMap').loadScript();
    },

    displayGmap: Ember.observer('googleMap.isLoaded', function () {
        if (!this.get('googleMap.isLoaded')) {
            return;
        }
        const mapOptions = this.mapOptions();
        this.set('map', new google.maps.Map(this.$()[0], mapOptions));
    }),

    handleResize: function () {
        if (!this.get('googleMap.isLoaded')){
            return;
        }
        const map = this.get('map');
        const center = map.getCenter();
        google.maps.event.trigger(map, 'resize');
        map.setCenter(center);
    },
});

import Ember from 'ember';

/**
 * Synchronize collection with map from component.
 * Care about to display or remove marker from map,
 * Be careful this is not optimized.
 **/
export
default Ember.Mixin.create({
    markers: null,
    _gHash: Ember.A(),
    init() {
        this._super.apply(this, arguments);
        /*
        * observes markers array.
        */
        this.get('markers').addArrayObserver({
            arrayWillChange: Ember.run.bind(this, this.markersWillChange),
            arrayDidChange: Ember.run.bind(this, this.markersDidChange)
        });
    },

    /*
    * Remove marker from array and remove from map
    */
    markerRemoved(marker) {
        let gMarker = this.get('_gHash').find(function(item) {
            return item.related === marker;
        });
        gMarker.native.setMap(null);
        this.get('_gHash').removeObject(gMarker);
    },

    /*
    * Add marker to `synchronized` array and display on map
    */
    markerAdded(marker) {
        const gMarker = new google.maps.Marker({
            position: {
                lat: marker.lat,
                lng: marker.lng
            },
            title: marker.title,
            map: this.get('map'),
        });
        this.get('_gHash').push({
            native: gMarker,
            related: marker
        });
    },

    /*
    * Take care about removed item
    */
    markersWillChange(markers, start, removeCount, addCount) {
        if (removeCount > 0) {
            for (let i = start; i < start + removeCount; i++) {
                this.markerRemoved(markers.objectAt(i));
            }
        }
    },

    /*
    * Take care about added item
    */
    markersDidChange(markers, start, removeCount, addCount) {
        if (addCount > 0) {
            for (let i = start; i < start + addCount; i++) {
                this.markerAdded(markers.objectAt(i));
            }
        }
    },
});

import Ember from 'ember';

const get = Ember.get;

/**
* This service lazy load googleMap api.
* Ugly but do the job
*/
export default Ember.Service.extend({

    scriptUrl: 'https://maps.googleapis.com/maps/api/js',
    isLoaded: Ember.computed.equal('state', 'loaded'),
    state: 'none',

    init: function () {
        let config = this.container.lookupFactory('config:environment');
        var apiKey = get(config, 'googleMap.apiKey');
        this.set('apiKey', apiKey);
    },

    normalizeUrl: function () {
        var url = this.get('scriptUrl');
        url += '?' + 'v=3' + '&' + 'libraries=places' + '&' + 'callback=loadGmap';
        if (this.get('apiKey')) {
            url += '&key=' + this.get('apiKey');
        }
        return url;
    },

    loadScript: function () {
        if (this.get('state') !== 'none'){
            return false;
        }
        this.set('state', 'loading');
        window.loadGmap = Ember.run.bind(this, function () {
            this.set('state', 'loaded');
        });
        var url = this.normalizeUrl();
        return Ember.$.getScript(url).fail(function(){
            console.log('getScript fail');
        });
    },
});

这项实施工作,但您必须清理&#39;这段代码:)

答案 1 :(得分:1)

1)创建一个组件,而不是视图

2)使用function startAvatarAnimation() { var avatarHeight = 250; var avatarTotalHeight = 2750; var i = 0; var avatarSpeed = 500; var avatarArray = {}; setInterval(function(){ i++; if(i > avatarArray.length){ i = 0; } $(".avatars").css({'background-position' : '0 -' + (i*avatarHeight) + 'px' }); }, avatarSpeed); } 呈现Google地图和观察者进行更新。不要忘记观察者是同步的(http://guides.emberjs.com/v1.13.0/object-model/observers/),你需要做像:

didInsertElement