Currently, I am developing a component that includes ng-map functionality by following the guidance in this tutorial.
<div class="content-pane" map-lazy-load="https://maps.google.com/maps/api/js" map-lazy-load-params="{{$ctrl.googleMapsUrl}}">
<ng-map class="content-pane" center="41,-87" zoom="5">
...
</ng-map>
</div>
While working on my controller, I encountered a common issue like this:
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < this.positions.length; i++) {
var latlng = new google.maps.LatLng(this.positions[i][0], this.positions[i][1]);
bounds.extend(latlng);
}
This led to an error stating 'google is not defined' as shown below:
angular.js:13708 ReferenceError: google is not defined
at new app.component.controller (map.component.js:13)
at Object.invoke (angular.js:4709)
at $controllerInit (angular.js:10234)
at nodeLinkFn (angular.js:9147)
at angular.js:9553
at processQueue (angular.js:16170)
at angular.js:16186
at Scope.$eval (angular.js:17444)
at Scope.$digest (angular.js:17257)
at Scope.$apply (angular.js:17552)
After some online research, I came across a related bug report in this link. The suggestion was to refer back to the tutorial example I had been using to resolve the issue, as it included script-tags-for-development.js which eagerly loads the required script. However, implementing this solution did not fully resolve the problem.
document.write([
'<script src="https://maps.google.com/maps/api/js?libraries=placeses,visualization,drawing,geometry,places"></script>',
...
Adding this script to the HTML resolved one issue but introduced another - 'Google Maps API error: MissingKeyMapError'. It became apparent that hardcoding the API key into the HTML head was not the ideal approach for me, as I required configurability within my Angular application.
To address the 'missing API key' error, I followed a helpful tutorial suggesting the use of a lazy-load directive. However, this brought me back to the initial problem I faced.
If you need to pass in an API key to the javascript, you can set a scope variable in your controller (e.g. $scope.googleMapsUrl="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY_HERE";). This can be set from a constant value in your app to standardise the API key to pass to google for multiple controllers.
<div map-lazy-load="https://maps.google.com/maps/api/js"
map-lazy-load-params="">
<ng-map center="41,-87" zoom="3"></ng-map>
</div>
Therefore, my question remains: How do the official ng-map tutorials/examples function without requiring a Google Maps API key? And how can I successfully overcome the 'google not found' error when utilizing the lazy-load directive instead of hardcoding the API key in the HTML head?