How use initial google map in Angularjs controller - angularjs

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.

Manipulating DOM from angular controller is not the Angular way of doing things. Depends on your needs, but I suggest you to take a look at Angular Google Maps or Angularjs-Google-Maps AngularJs modules. They both provide set of directives, which you can use in your html code and then access map object exposed on scope in controller to manipulate your map.

Related

Angularjs implementing google maps not being rendered

I'm trying to include google maps in my side-project and i can't seem to know why this doesn't work after watching countless tutorials. One way I was able to do a work around was to include the src script in right below the init function on the html and then on the controller file write the initMap() function outside the
angular.module('breazehomeDesktop').controller(). Can someone please help?
this is my html
!doctype html>
<html>
<head>
<!-- Tab Title -->
<title>Local Scoop</title>
<!-- Javascript Import-->
<script src="../scripts/controllers/localscoop.js"></script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=KEY_GOES HERE"></script>
</head>
<body ng-app="breazehomeDesktop" ng-controller="LocalScoopCtrl">
<!-- MAP -->
<div id="map" ng-init="initMap()">
<script>initMap()</script>
</div>
</body>
</html>
and this is my controller
angular.module('breazehomeDesktop').controller('LocalScoopCtrl', function($scope, $rootScope, $location, $localStorage, $routeParams, $anchorScroll, $http, Properties, Amenities, Bilingual,toasts,Users,Crime, Map, BASE_URL, IMAGE_URL, ModalService, History) {
$scope.initMap = function (){
var map = new google.maps.Map(document.getElementById('map'),{
zoom:8,
center: {
latitude:25.7617,
longitude:-80.191790
}
}
)};
});
I do not see anywhere you've mentioned ng-controller and use ng-init to call the method
<body ng-app="breazehomeDesktop" ng-controller="LocalScoopCtrl">
<div id="map" ng-init="initMap()" >
</div>

Angular Google Maps won't show anything

From what I gather the below code is the minimum necessary to run Angular Google Maps, but it won't show the map on screen. Looking at #my-map component in Chrome, it shows 0x0px and I haven't been able to change that despite the css and dynamic height declarations. Apart from that it seems to be running fine, there are no console errors and the appMaps module is at least initialized correctly.
<!DOCTYPE html>
html>
<head>
<title>New Map</title>
<style>
html, body {
height: 2000px;
width: 100%;
margin: 0;
padding: 0;
}
.angular-google-map-container { height: 400px; }
</style>
<script src="lodash/lodash.js"></script>
<script src="angular/angular.js"></script>
<script src="angular-google-maps/dist/angular-google-maps.js"></script>
<script>
var appMaps = angular.module('appMaps', ['uiGmapgoogle-maps']);
appMaps.config(function(uiGmapGoogleMapApiProvider) {
uiGmapGoogleMapApiProvider.configure({
key: 'My Key Is Entered Here',
v: '3.20',
libraries: 'weather,geometry,visualization'
});
});
appMaps.controller('mainCtrl', function($scope) {
$scope.map = { center: { latitude: 45, longitude: -73 }, zoom: 8 };
$scope.$on('$viewContentLoaded', function () {
var mapHeight = 400; // or any other calculated value
$("#my-map .angular-google-map-container").height(mapHeight);
});
});
</script>
</head>
<body>
<h1>TEST</h1>
<div id="map_canvas" ng-controller="mainCtrl">
<ui-gmap-google-map id="my-map" center="map.center" zoom="map.zoom"></ui-gmap-google-map>
</div>
</body>
</html>
Edit: Yep, so Roux was correct, added the google maps API script (with key) at the top and angular-simple-logger after angular and that lead me pretty close. Then I just needed to add ng-app="appMaps" to the body element (I'm new to angular in general) and it worked. Thanks!
By following the Quickstart, you can see that you missed to call a few library/api.
Add the angular-simple-logger.js in your project (I think it comes with angular-ui packages or angular-google-maps)
Don't forget to add the google api, without it, nothing will work. <script src='//maps.googleapis.com/maps/api/js?sensor=false'></script>

Using maxBounds to stop panning in Leaflet with angular-leaflet-directive

Now that I have my AngularJS application running, I'm trying to restrict LeafletJS map panning as described in this Mapbox document. The issue is that I am using angular-leaflet-directive and my existing code is written to create the map using the leaflet directive in my AngularJS template. So the existing map is defined in this fashion:
<leaflet id="mymap" markers="markers" center="center" width="100%" height="380px"></leaflet>
How do I getBounds() and setMaxBounds() in a situation like this, where I never explicitly did a call to new L.map('leaflet', {...}))?
bounds and maxBounds properties could be set via angular-leaflet-directive using maxBounds and bounds directives respectively, for example:
<leaflet markers="markers" maxbounds="boundsInfo" bounds="boundsInfo"></leaflet>
where bounds should be specified in the following format:
$scope.boundsInfo = {'northEast': {'lat': 40.774, 'lng': -74.125},'southWest': {'lat': 40.712, 'lng': -74.227}};
Example
angular.module("demoapp", ["leaflet-directive"])
.controller("CustomizedMarkersController", ['$scope','leafletData', function ($scope, leafletData) {
$scope.boundsInfo = {'northEast': {'lat': 40.774, 'lng': -74.125},'southWest': {'lat': 40.712, 'lng': -74.227}};
$scope.markers = [];
leafletData.getMap().then(function (map) {
console.log(map.getBounds());
});
}]);
.angular-leaflet-map {
width: 640px;
height: 480px;
}
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.0.1/dist/leaflet.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script type="text/javascript" src="https://code.angularjs.org/1.2.2/angular.js"></script>
<script type="text/javascript" src="https://tombatossals.github.io/angular-leaflet-directive/dist/angular-leaflet-directive.js"></script>
<script src="https://unpkg.com/leaflet#1.0.1/dist/leaflet.js"></script>
<div ng-app="demoapp" ng-controller="CustomizedMarkersController">
<leaflet markers="markers" maxbounds="boundsInfo" bounds="boundsInfo" maxZoom="19" minZoom="10"></leaflet>
</div>

Display OpenLayers map using ng-view AngularJS

I am building an AngularJS app which exposes an OpenLayers map. I used this simple example (literally just copy and pasted into an HTML file) ran it in the browser and - no surprise - it worked.
I then added the AngularJS Wrapping to it so that I could include it in a partial declared and routed to via app.js (below) and the OpenLayers library doesn't seem to be working any more. I am not getting errors in the console (running it on IE11) but I am not getting a visible map either. I have tried substituting the map for some simple data binding in the controller and it's working, and I am getting the sub-heading displayed just above the map too.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>AngularJS Tutorial</title>
<link rel="stylesheet" href="http://openlayers.org/en/v3.11.2/css/ol.css" type="text/css">
<script src="http://openlayers.org/en/v3.11.2/build/ol.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.min.js"></script>
<script src="app.js"></script>
<script src="main.ctrl.js"></script>
<style>
.map {
height: 400px;
width: 100%;
}
</style>
</head>
<body ng-app="app" ng-controller="MainController">
<h1>Map Viewer</h1>
<div ng-view></div>
</body>
</html>
app.js
angular.module("app", ["ngRoute"])
.config(function($routeProvider){
$routeProvider
.when("/main", {
templateUrl: "main.html",
controller: "MainController"
})
.otherwise({redirectTo: "/main"});
});
main.html
<h2>My Map</h2>
<div id="map" class="map"></div>
<script type="text/javascript">
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.MapQuest({layer: 'sat'})
})
],
view: new ol.View({
center: ol.proj.fromLonLat([37.41, 8.82]),
zoom: 4
})
});
</script>
main.ctrl.js
angular.module("app")
.controller("MainController", function($scope){
//Do something
});
If you consider in using directives check this
Plunker
EDIT
I modified it for a more simple use
angular.module("app")
.controller("MainController", function($scope){
//Do something
})
.directive('mapDir', function () {
return {
restrict: 'A',
link: function ($scope) {
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.MapQuest({layer: 'sat'})
})
],
view: new ol.View({
center: ol.proj.fromLonLat([37.41, 8.82]),
zoom: 4
})
});
}
};
});
and view
<h2>My Map</h2>
<div map-dir id="map" class="map"></div>
Tell me if it was this what you are looking for

Displaying google maps in angular.js

I might be making a really silly mistake here, but I'm not sure where I'm going wrong. Just trying to get a simple map to display on page with google maps and angular.js.
Here is my controller..
var myApp = angular.module('myApplicationModule', ['google-maps']);
myApp.controller('IndexController', ['$scope', function ($scope) {
$scope.map = {
center: {
latitude: 45,
longitude: -73
},
zoom: 8
};
}]);
And here is my html page..
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" ng-app="myApplicationModule">
<head>
<title></title>
</head>
<body ng-controller="IndexController">
<google-map center="map.center" zoom="map.zoom"></google-map>
<script src='//maps.googleapis.com/maps/api/js?sensor=false'></script>
<script src='/Scripts/lodash.js'></script>
<script src='/Scripts/angular-google-maps.js'></script>
<script src='/Scripts/angular.js'></script>
</body>
</html>
I have included all the necessary scripts and gotten angular.js from NuGet, declared my application and specified the controller.
However, the map is not displaying on the page.. Anybody able to point out why?

Resources