angular, google maps. map not loading with template - javascript

I am having trouble loading a google map, while using angular routes with a template. As the code currently stands if i navigate to "#/map" the google map does not show up and inspecting the element, the map information is not there but the template loads as the h1 tag 'Map' does load. However, if I take the code from my map template and put it into my index.html it works perfectly fine. Does anyone know why this is and how to fix it?
Here is my index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Ski</title>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
</head>
<body ng-app="Ski">
<ng-view></ng-view>
<!-- app and routes -->
<script src="js/app.js"></script>
<script src="js/routes.js"></script>
<!-- controllers -->
<script src="js/controllers/map.controller.js"></script>
</body>
</html>
This is my template for map.
<div>
<h1> Map </h1>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=xxxxxxxxxxxxxxxxxxxx">
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: { lat: -34.397, lng: 150.644},
zoom: 8
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="map-canvas" style="width: 50%; height: 50%;"></div>
</div>
My angular module.
angular.module('Ski', ['ngRoute']);
My angular routes.
angular.module('Ski').config(function($routeProvider) {
'use strict';
$routeProvider
.when('/home', {
templateUrl: 'templates/home.html'
})
.when('/map', {
templateUrl: 'templates/map.html'
})
.otherwise({
redirectTo: '/'
});
});

The problem is that when map view is loaded window.load event has already occurred, so this line
google.maps.event.addDomListener(window, 'load', initialize);
won't invoke initialize function, because load event is not going to happen again.
Instead try to move map script into head section:
<head>
<meta charset="utf-8">
<title>Ski</title>
<script src="https://maps.googleapis.com/maps/api/js?key=xxxxxxxxxxxxxxxxxxxx"></script>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
</head>
and then write simple directive to initialize map in map template:
<div>
<h1>Map</h1>
<map-canvas id="map" style="width: 50%; height: 50%;"></map-canvas>
</div>
The mapCanvas directive will look then something like this:
angular.module('Ski').directive('mapCanvas', function() {
return {
restrict: 'E',
link: function(scope, element) {
var mapOptions = {
center: { lat: -34.397, lng: 150.644},
zoom: 8
};
new google.maps.Map(element[0], mapOptions);
}
};
});
Demo: http://plnkr.co/edit/370NBWS3YlTrGBqK7riT?p=preview

Related

AngularJS Error: $injector:modulerr Module Error when trying to use OpenLayers directive

I'm having issues where my module is not loading my map, giving an Error: $injector:modulerr
Module Error. I'm fairly certain I instantiated my module correctly with...
var app = angular.module("MapApp", ["openlayers-directive"]);
app.controller('MapController', ['$scope', function MapController($scope){
angular.extend($scope, {
center:{
lat: 40.060620,
lon: -77.523182,
zoom: 17
}
});
}]);
And then use this within my html...
<!DOCTYPE html>
<html lang="en" ng-app="MapApp">
<head>
<meta charset="UTF-8">
<title>ShipList</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.4.2/css/bulma.css">
<link rel="stylesheet" href="../css/main.css">
<script src="../js/ol.js"></script>
<script src="../lib/angular.min.js"></script>
<link rel="stylesheet" href="../css/ol.css"/>
<script src="../js/Map.js"></script>
...
<!--Later in my body tag, I'm declaring my Controller-->
<div class="overlay" ng-controller="MapController">
<openlayers id="mapid"></openlayers>
But I'm still getting the module instantiation error. I think I'm not loading the OpenLayers directive correctly? I also tried loading the same dependencies from CDNs for OpenLayers and such see here in this JSFiddle. If it matters, I also defined the height, width, and zoom properties of my map in my style sheet.
.angular-openlayers-map {
height: 800px;
width: 100%;
float: left;
z-index: 1;
position: relative;
}
I don't see any references for open layers javascript file. Please check the following demo.
Demo
var app = angular.module("demoapp", ["openlayers-directive"]);
app.controller("DemoController", [ '$scope', function($scope) {
$scope.showDetails = function(id) {
alert('lat: '+ id.lat+', '+'lon: '+id.lon);
};
angular.extend($scope, {
center: {
lat: 42.9515,
lon: -8.6619,
zoom: 9
},
finisterre: {
lat: 42.907800500000000000,
lon: -9.265031499999964000,
label: {
show: false,
},
onClick: function (event, properties) {
alert('lat: '+ properties.lat+', '+'lon: '+properties.lon);
}
},
santiago: {
lat: 42.880596200000010000,
lon: -8.544641200000001000,
label: {
show: true
}
},
santacomba: {
lat: 43.0357404,
lon: -8.8213786,
label: {
message: "Santa Comba",
show: false,
},
onClick: function (event, properties) {
alert('lat: '+ properties.lat+', '+'lon: '+properties.lon);
}
}
});
}]);
<!DOCTYPE html>
<html ng-app="demoapp">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ol3/3.7.0/ol.min.js"></script>
<script src="https://code.angularjs.org/1.4.0/angular.min.js"></script>
<script src="https://code.angularjs.org/1.4.0/angular-sanitize.min.js"></script>
<script src="https://tombatossals.github.io/angular-openlayers-directive/dist/angular-openlayers-directive.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ol3/3.7.0/ol.min.css" />
<link rel="stylesheet" href="http://tombatossals.github.io/angular-openlayers-directive/dist/angular-openlayers-directive.css" />
<!-- Demo Styles -->
<link rel="stylesheet" href="style.css" />
</head>
<body ng-controller="DemoController">
<h1>Open Layers Demo</h1>
<p>Click on the <em>map marker</em> for <strong>Fisterra</strong> or <strong>Santa Comba</strong>to see the latitude and longitude.</p>
<p>Click on the map marker <em>popover</em> for <strong>Santiago de Compostela</strong> to see the latitude and longitude.</p>
<openlayers ol-center="center" height="400px" width="100%">
<ol-marker ol-marker-properties="santiago"><p ng-click="showDetails(santiago)">Santiago de Compostela</p></ol-marker>
<ol-marker ol-marker-properties="finisterre" class="hidden"><span></span></ol-marker>
<ol-marker ol-marker-properties="santacomba"></ol-marker>
</openlayers>
</body>
</html>

GoogleMaps doesn't appear when Angular ui-router($stateProvider) is used

I have three states in my simple ionic project. I want to add a map to home page after logged in. When I tried to add a map in map.html file which is a template file, it appears when map.html opened via browser. However, when I try to reach this state(map.html) by using $stateProvider the map does not appear.
My map.html file is :
<!DOCTYPE html>
<html ng-app="starter">
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script async defer src="https://maps.googleapis.com/maps/api/js?key=APIKEY&callback=initMap"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 400px;
}
</style>
</head>
<body ng-controller="mapctrl">
<ion-header-bar class="bar-dark"> <h1 class="title">Home Page</h1></ion-header-bar>
<ion-view>
<div id="map" ng-init="initMap()"></div>
<button ng-click="goOther()" class="button button-block button-dark">For more detail please click!</button>
</ion-view>
</body>
</html>
My app.js is :
var app =angular.module('starter', ['ionic'])
app.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
})
app.config(['$stateProvider','$urlRouterProvider',function($stateProvider,$urlRouterProvider){
$stateProvider
.state('login',{
url:'/login',
templateUrl:'templates/login.html',
controller:'loginctrl'
})
.state('map',{
url:'/map',
templateUrl:'templates/map.html',
controller:'mapctrl'
})
.state('other',{
url:'/other',
templateUrl:'templates/other.html',
controller:'otherctrl'
})
$urlRouterProvider.otherwise('/login');
}])
app.controller('loginctrl',function($scope,$state){
$scope.goMap = function(){$state.go('map');};
})
app.controller('mapctrl',function($scope,$state){
$scope.goOther = function(){
$state.go('other');};
$scope.initMap = function () {
console.log("deneme");
var myLatlng = new google.maps.LatLng(51.5120, -0.12);
var mapOptions = {
zoom: 14,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
google.maps.event.addDomListener(window, "resize", function() {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
};
})
app.controller('otherctrl',function($scope,$state){
$scope.goLogin = function(){$state.go('login');};
});
I've also tried to add the map directly in map.html file but it doesn't appear,either.
Thanks in advance.
Google maps works only with https in chrome and it may not have any dependency with $stateProvider

AngularJs with Google Maps

I have this code because I want inlude the Google maps in my webApp but don't work. This is the page html:
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="js/libs/angular.js/angular.js"></script>
<script src="js/libs/angular.js/angular-route.js"></script>
<script src="http://maps.google.cn/maps/api/js?sensor=false"></script>
<script src="js/libs/mappa/lodash.js"></script>
<script src="js/libs/mappa/angular-google-maps.min.js"></script>
</head>
<body>
<div>
<ui-gmap-google-map center=map.center zoom=map.zoom style="width: 400px; height: 400px;"></ui-gmap-google-map>
</div>
</body>
</html>
This is my controller in AngularJs:
var modulo = angular.module('progetto', ['ngRoute', 'uiGmapgoogle-maps']);
modulo.controller('descriptionController', function ($scope, $routeParams, $http) {
$scope.map = { center: { latitude: 45, longitude: -73 }, zoom: 8 };
}).
error(function (data, status) {
$scope.listaEventi = "Request failed";
});
Where is the error? I think that i import exact library!
You're missing quotes around your html attributes...
You're missing ng-app
You're missing ng-controller
You're calling .error on your controller (?)
You need to define this css rule:
.angular-google-map-container { height: 400px; }
Inline style on your directive is not good enough.
Please check your js error console next time. Your statement of "there are no errors" is most likely not true.
Here's a working fiddle... http://jsfiddle.net/ybtn4kn2/
You seem to have forgotten your
<div ng-controller="descriptionController">
And you will need to pass in the library to the controller
.controller("descriptionController", function($scope, uiGmapGoogleMapApi)

Google Maps Routing W/ AngularJS

I have created an app that uses Google Maps, the map showed up before I did my routing. But after routing it wont display. Here is my code for the app.
JS:
search-controller.js
(function() {
searchController.$inject = ['$scope'];
function searchController($scope) {
$scope.ASiteLocs = [There Is Code In here that is too long and irrelevant to the map];
$scope.SSiteLocs = [""];
$scope.SiteLocs = $scope.SSiteLocs.concat($scope.ASiteLocs);
angular.forEach($scope.SiteLocs, function(location) {
var clength = location.Point.coordinates.length;
if (location.Point.coordinates.substring(clength - 2, clength) === ",0") {
location.Point.coordinates = location.Point.coordinates.substring(0, clength - 2).split(",");
Lat = location.Point.coordinates[0];
Lon = location.Point.coordinates[1];
Com = ",";
location.Point.coordinates = Lon.concat(Com, Lat);
}
angular.forEach($scope.SSiteLocs, function(object) {
object.carrier = 'Sprint';
});
angular.forEach($scope.ASiteLocs, function(object) {
object.carrier = 'AT&T';
});
});
}
angular.module("siteLookUpApplication").controller('searchController', searchController);
}());
map-controller.js
(function() {
mapController.$inject = ['$scope', '$routeParams'];
function mapController($scope, $routeParams) {
function initialize() {
var mapOptions = {
center: site.Point.coordinates,
zoom: 5
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
// Save the locationName in the url to the scope
$scope.locationName = $routeParams.locationName;
}
angular.module("siteLookUpApplication").controller("mapController", mapController);
}());
app.js
(function() {
angular.module("siteLookUpApplication", ["ngRoute"]);
angular.module("siteLookUpApplication").config(function($routeProvider) {
$routeProvider
.when("/search", {
templateUrl: "search.html",
controller: "searchController"
})
.when("/map/:locationName", {
templateUrl: "map.html",
controller: "mapController"
})
.otherwise({
redirectTo: '/search'
});
});
}());
HTML:
map.html
<style>
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100%
background:#fff;}
</style>
<div>
<div><a ng-href="#/search">Back To Search</a></div>
<p>Map for {{locationName}}</p>
<div id="map-canvs"></div>
</div>
index.html
<!DOCTYPE html>
<html ng-app="siteLookUpApplication">
<head>
<link href='http://fonts.googleapis.com/css?family=Droid+Serif' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="style.css" type='text/css'/>
<script data-require="angular.js#*" data-semver="1.2.17" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.js"></script>
<script data-require="jquery#*" data-semver="2.1.1" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<script data-require="google-maps#1.0.0" data-semver="1.0.0" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script data-require="angular-route#*" data-semver="1.2.17" src="http://code.angularjs.org/1.2.17/angular-route.js"></script>
<script src="app.js"></script>
<script src="map-controller.js"></script>
<script src="search-controller.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC0wdLb9-Os4YVxn_JR2sY08xEN-1aJkMM"></script>
<title>Site ID</title>
</head>
<body link="white" vlink="white">
<div class="text-center">
<h1>Site Finder</h1>
<div id="map-canvas"></div>
<div ng-view></div>
</div>
</body>
</html>
search.html
<div>
<input type="text" ng-model="search" border="1" placeholder="Please enter site name..." />
<table border="1" width="100%">
<thead>
<tr>
<td>Name</td>
<td>Carrier</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="site in SiteLocs | filter : search">
<td>
<a ng-href="#/map/{{site.name}}">
{{site.name}}
</a>
</td>
<td>
{{site.carrier}}
</td>
</tr>
</tbody>
</table>
</div>
Here is a plunk with my project if that is easier: http://plnkr.co/edit/AiVc6nccqke8Jluonpxl?p=info
You have a few problems:
The Google Maps api is loaded twice
Google Maps should be loaded before Angular
jQuery should be loaded before Angular
In the map.html the div id has a typo
In the maps controller "site" is unresolved (for the center property)
map-canvas exists in the index.html (this should be removed)
In the map controller the initialize function is declared but never called
The CSS on the actual map element is a little wonky and will not display -- for testing put a static height on it or something
App Structure notes:
When using document and window you should instead inject $document and $window
Perhaps you can use a directive for the map instead of a controller -- see http://angular-google-maps.org/
The filtered list looks pretty long consider using ReactJS or pagination.
executiveLiveTracking(executive) {
debugger
let isOpenLiveTracking = executive !== undefined ? PreventMapRendering(executive.deliveryExecutiveId, true) : false;
if (isOpenLiveTracking) {
this.setState({
isLengthExceededMap: false,
DeliveryExecutiveId: executive.deliveryExecutiveId,
liveTrackingModalVisible: true,
snapPointList: [],
liveTrackingExecutiveName: executive.executiveName,
liveTrackingExecutiveLat: executive.executiveLatitude,
liveTrackingExecutiveLng: executive.executiveLongitude
});
}
else {
MessageBox(Constants.ERROR_MSG_FOR_MAP_RENDERING, Constants.INFO);
}

jQuery mobile add new markers to an existing map

I am working with the jQuery mobile google maps example here, focusing on the first "Basic Map Example".
http://jquery-ui-map.googlecode.com/svn/trunk/demos/jquery-google-maps-mobile.html
I want to be able to dynamically add markers to the basic_map, but I am having some trouble. I'm new to jQuery mobile and JavaScript.
Here is my edited version of the basic-map example from the jQuery mobile UI website. If you save it in the jQuery mobile demos folder, then everything should render properly. I have added a button at the bottom of the map page and also the addMarkers function. When you load the page, the map shows up centered at the mobileDemo coordinates (-41, 87), which is close to chicago, but not quite there. When you click on the button, I want to update the map with another marker at the chicago point, but the screen goes blank.
This is just a mock example of what I really want to do. In my longer, more complicated program, I'm querying a database to find addresses that match the query, then I want to put those markers up on the map dynamically. What do I need to change about this source code to be able to plot the Chicago point (or other markers on the fly)?
<!doctype html>
<html lang="en">
<head>
<title>jQuery mobile with Google maps - Google maps jQuery plugin</title>
<link type="text/css" rel="stylesheet" href="css/jquery-mobile-1.0/jquery.mobile.css" />
<link type="text/css" rel="stylesheet" href="css/mobile.css" />
<script type="text/javascript" src="js/modernizr-2.0.6/modernizr.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript" src="js/jquery-1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery-mobile-1.0/jquery.mobile.min.js"></script>
<script type="text/javascript" src="js/jquery.ui-1.8.15/jquery.ui.autocomplete.min.js"></script>
<script type="text/javascript" src="js/demo.js"></script>
<script type="text/javascript" src="../ui/jquery.ui.map.js"></script>
<script type="text/javascript" src="../ui/jquery.ui.map.services.js"></script>
<script type="text/javascript" src="../ui/jquery.ui.map.extensions.js"></script>
<script type="text/javascript">
var mobileDemo = { 'center': '41,-87', 'zoom': 7 };
var chicago = new google.maps.LatLng(41.850033,-87.6500523);
var map
function addMarkers(){
map = new google.maps.Map(document.getElementById('map_canvas'));
var marker = new google.maps.Marker({
map: map,
position: chicago
});
}
$('#basic_map').live('pageinit', function() {
demo.add('basic_map', function() {
$('#map_canvas').gmap({'center': mobileDemo.center, 'zoom': mobileDemo.zoom, 'disableDefaultUI':true, 'callback': function() {
var self = this;
self.addMarker({'position': this.get('map').getCenter() }).click(function() {
self.openInfoWindow({ 'content': 'Hello World!' }, this);
});
}});
}).load('basic_map');
});
$('#basic_map').live('pageshow', function() {
demo.add('basic_map', function() { $('#map_canvas').gmap('refresh'); }).load('basic_map');
});
</script>
</head>
<body>
<div id="basic_map" data-role="page">
<div data-role="header">
<h1><a data-ajax="false" href="/">jQuery mobile with Google maps v3</a> examples</h1>
<a data-rel="back">Back</a>
</div>
<div data-role="content">
<div class="ui-bar-c ui-corner-all ui-shadow" style="padding:1em;">
<div id="map_canvas" style="height:350px;"></div>
</div>
</div>
<div data-role="content">
Add Some More Markers
</div>
</div>
</body>
</html>
Please check the below example.
In the first map load there isn't any marker. When you click the button then a marker is dynamically added without a need for page or map refresh.
<!doctype html>
<html lang="en">
<head>
<title>jQuery mobile with Google maps - Google maps jQuery plugin</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3&sensor=false&language=en"> </script>
<script type="text/javascript" src="http://jquery-ui-map.googlecode.com/svn/trunk/ui/min/jquery.ui.map.min.js"></script>
<script type="text/javascript">
var chicago = new google.maps.LatLng(41.850033,-87.6500523),
mobileDemo = { 'center': '41,-87', 'zoom': 7 };
function initialize() {
$('#map_canvas').gmap({ 'center': mobileDemo.center, 'zoom': mobileDemo.zoom, 'disableDefaultUI':false });
}
$(document).on("pageinit", "#basic-map", function() {
initialize();
});
$(document).on('click', '.add-markers', function(e) {
e.preventDefault();
$('#map_canvas').gmap('addMarker', { 'position': chicago } );
});
</script>
</head>
<body>
<div id="basic-map" data-role="page">
<div data-role="header">
<h1><a data-ajax="false" href="/">jQuery mobile with Google maps v3</a> examples</h1>
<a data-rel="back">Back</a>
</div>
<div data-role="content">
<div class="ui-bar-c ui-corner-all ui-shadow" style="padding:1em;">
<div id="map_canvas" style="height:350px;"></div>
</div>
Add Some More Markers
</div>
</div>
</body>
</html>
The initial map:
The map after the button's click:

Categories