I would like to implement below google sample inside my angular controller.
https://developers.google.com/maps/documentation/javascript/examples/map-simple
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap"
async defer></script>
</body>
</html>
Wherein the load of google map api needs a initMap to be followed inside the window scope.
How should I do inside angular controller? Code below does not work:
angular.module('testApp')
.controller('MainCtrl', function ($scope, $window) {
$window.map;
$window.initMap = function() {
$window.map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
}
});
Add your API key and remove callback=initMap in:
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>
Remember to load the maps library at the end of the <body></body>
in your html page to make sure all your other libraries are loaded first.
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY></script>
Then initialise the map manually calling the initMap function triggering it from somewhere in your code.
Just note that doing in this synchronous way your app will be blocked until the maps library is completely loaded which can slow down your application.
Depending on your inclusion order of the maps library, you can either call it directly like this:
HTML:
<div ng-app="testApp" id="map" ng-controller="MainCtrl"></div>
Javascript:
var app = angular.module('testApp', [])
.controller('MainCtrl', function ($scope, $window) {
$window.map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 8
});
});
Demo: http://jsfiddle.net/uxe4b9uu/
Alternatively you can get the maps to initialize on callback as you had suggested provided that you know you have loaded Angular before the map library.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With