Reputation: 6246
I have this code in my controller
$scope.initMap = function() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
}
$timeout(function(){$scope.initMap();}, 1); //This works
//$scope.initMap(); //Doing it like this causes the crash
Using the $timeout line the map is initialized fine, but using the bottom line Angular throws an error a is null
, from somewhere inside the minified library.
I'm including the Google Maps js file just above my controller in the HTML
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MyKey& sensor=false"></script>
<div class="row" ng-controller="VenuesCtrl">
I assume it's something to do with the $timeout function rather than needed to wait for 1 millisecond, but I can't figure it out. Do I need the $timeout or can I make my code work without it?
Upvotes: 0
Views: 127
Reputation: 77930
It happens because Google tries to use id DOM element before map-canvas element is rendered. I would create directive and call Google Map constructor from there
I think even with $timeout
0
it works too.
The function wrapped by $timeout
executes after every other piece of code following the call to $timeout is executed.
Why it works?
With timeout you just level down execution priority. Its a trick to tell the browser to run it ASAP when other stuff done and browser is not busy.
You can google enough examples and demos how to write Google Map constructor with directive. I use my own.
Here is a relevant code:
HTML
<map-directive id="map_canvas" >
</map-directive>
directive
app.directive('mapDirective', ['$log', function($log) {
return {
restrict: 'E',
replace: true,
scope: {
/* ... */
},
template: '<div></div>',
link: function(scope, element, attrs) {
var map = false;
//...
initialize(document.getElementById(attrs.id));
function initialize(map_id) {
log.i("initialize Google maps");
var mapZoomLevel = locStorage.get('mapZoomLevel', 12);
var mapLast_lat = locStorage.get('mapLast_lat', 34.060122481016855);
var mapLast_longt = locStorage.get('mapLast_longt', -118.26350324225484);
var options = {
zoom: mapZoomLevel,
center: new google.maps.LatLng(mapLast_lat, mapLast_longt),
mapTypeId: google.maps.MapTypeId.ROADMAP,
panControl: false,
scrollwheel: true,
draggable: true,
rotateControl: false,
mapTypeControl: true,
scaleControl: true,
streetViewControl: true,
zoomControl: true,
disableDoubleClickZoom: false
};
map = new google.maps.Map(document.getElementById(attrs.id), options);
//...
}
Upvotes: 1