Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Maps load API script and initialize inside ember.js view

I'm trying to create a Ember View for Google Maps, and load the script in a on-demand manner, i.e. asynchronously Loading the API.

I have two functions inside the view, one is used to load the Google Maps API and the other is to initialize the map. But since Google requires me to call the callback function through the link that requires the API. But in Ember.JS, I couldn't get the right result. All I've got is an ERROR message saying that the object "google" is undefined when trying to initialize the map.

Here is the Ember view code for now.

App.MapsView = Ember.View.extend({

templateName: 'maps',
map: null,

didInsertElement: function() {
    this._super();
    this.loadGoogleMapsScript();
},

initiateMaps: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(this.$().get(0), mapOptions);
    this.set('map',map);
},

loadGoogleMapsScript: function(){
    var map_callback = this.initiateMaps();

    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=map_callback';
    document.body.appendChild(script);
},

});

Any ideas how to solve this callback problem? And, what is the optimal way to initialize the map? Should it be in the template or from the JS?

Thanks in advance.

like image 240
ANY507 Avatar asked Jun 12 '13 21:06

ANY507


1 Answers

There are two problems here. One is that you're calling your initiateMaps() function in this line:

var map_callback = this.initiateMaps();

This call is made before the Maps API is loaded, leading to the undefined google error.

The other problem is that map_callback is local to this function. The callback used in the Maps API script URL has to be a global function.

(You solved this problem yourself; I'm just adding it here for the benefit of future visitors.)

The fix for both of these problems is to change that line to:

var self = this;
window.map_callback = function() {
    self.initiateMaps();
}

There may be a more "native" Ember way to do this, but that should do the trick in any case.

Also, since you're using jQuery along with Ember, you can replace this code:

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=map_callback';
document.body.appendChild(script);

with:

$.getScript( 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=map_callback' );
like image 178
Michael Geary Avatar answered Oct 05 '22 13:10

Michael Geary