AngularJS: Route displaying blank page - angularjs

I have a route/view that is displaying a blank page. I am pretty sure it was working the way I have it right now a few days ago which leads me to think it is a problem with my Google Maps API key, but there are no errors or warnings so I think it has to do with my routing setup. But I have another view set up exactly the same way and that one does work...
Broken view: http://alainwebdesign.ca/pl2/#/49.2/-122.66
Working view: http://alainwebdesign.ca/pl2/#/getLocation
Controller (I commented out the.config for Google Map API because I have a script reference in my view searchRadius.html) :
(function (window, ng) {
ng.module('app', ['uiGmapgoogle-maps', 'ui.router'])
.config(function ($stateProvider) { //had: , $stateChangeError included in the function parameters, but that caused error
$stateProvider.state('searchRadius', {
url: '/:lat/:lon',
templateUrl: 'searchRadius.html', //changed from index to searchRadius.html
controller: 'MapsCtrl',
});
})
////ALREADY HAVE GOOGLE MAPS KEY ON searchRadius.html
.config(['uiGmapGoogleMapApiProvider', function (GoogleMapApi) {
GoogleMapApi.configure({
key: 'AIzaSyC_XEbbw3sNm4XlLAgqMJTggeHLDUdV-pY',
v: '3',
libraries: 'weather,geometry,visualization'
});
} ])
.controller('MapsCtrl', ['$scope', "uiGmapLogger", "uiGmapGoogleMapApi", "$interval", "$state", "$stateParams",
function ($scope, $log, GoogleMapApi, $interval, $state, $stateParams) {
$log.currentLevel = $log.LEVELS.debug;
var center = { latitude: parseFloat($stateParams.lat), longitude: parseFloat($stateParams.lon) };
alert(JSON.stringify(center));
Object.freeze(center); //caused TypeError: Cannot assign to read only property ('latitude') ...
console.log($stateParams);
$scope.map = {
center: center,
pan: false,
zoom: 16,
refresh: false,
events: {},
bounds: {}
};
$scope.map.circle = {
id: 1,
center: center,
radius: 500, //(current time - date lost)*km/hour
stroke: {
color: '#08B21F',
weight: 2,
opacity: 1
},
fill: {
color: '#08B21F',
opacity: 0.5
},
geodesic: false, // optional: defaults to false
draggable: false, // optional: defaults to false
clickable: true, // optional: defaults to true
editable: false, // optional: defaults to false
visible: true, // optional: defaults to true
events: {
dblclick: function () {
$log.debug("circle dblclick");
},
radius_changed: function (gObject) {
var radius = gObject.getRadius();
$log.debug("circle radius radius_changed " + radius);
}
}
}
//Increase Radius:
$interval(function(){
$scope.map.circle.radius += 30; //dynamic var
}, 1000); //end of interval function
} ]); //end of controller
})(window, angular);
searchRadius.html:
<div style="height: 100%"> <!--took out: ng-if="map.center !== undefined"-->
<ui-gmap-google-map
center='map.center'
zoom='map.zoom'
draggable='map.draggable'
dragging='map.dragging'
refresh='map.refresh'
options='map.options'
events='map.events'
pan='map.pan'>
<ui-gmap-circle
center='map.circle.center'
radius='map.circle.radius'
fill='map.circle.fill'
stroke='map.circle.stroke'
clickable='map.circle.clickable'
draggable='map.circle.draggable'
editable='map.circle.editable'
visible='map.circle.visible'
events='map.circle.events'>
</ui-gmap-circle>
</ui-gmap-google-map>
<script src='//maps.googleapis.com/maps/api/js?key=AIzaSyC_XEbbw3sNm4XlLAgqMJTggeHLDUdV-pY'></script>
</div>

Combine the 2 files into 1 file and initialize the $stateProvider in a single line.

Related

Angular js ngclick doesnt work in infowindow

I created a map with Google maps. At first the infowindow is open when the init function is called. I select a place from the map $scope.kds is working and the contents of the infowindow change. There is a button in the infowindow. When I click the button doesnt work. How can I do?
window.ngApp = angular.module('test', []);
window.ngApp.controller('controllerMap', ['$scope', '$location', '$compile', function ($scope, $location, $compile) {
$scope.init = function () {
$scope.latlng = new google.maps.LatLng($scope.lat, $scope.lng);
$scope.map = new google.maps.Map(document.getElementById('map'), {
center: $scope.latlng,
zoom: $scope.zoom,
minZoom: 6,
maxZoom: 21
});
$scope.marker = new google.maps.Marker({
map: $scope.map,
position: $scope.latlng,
draggable: true,
icon: 'static/img/pin-4ldpi.png'
});
$scope.infowindow = new google.maps.InfoWindow({
content: "",
maxWidth: 175
});
google.maps.event.addListener($scope.map, 'click', function (event) {
$scope.kds ();
});
$scope.kds = function(){
$.ajax({
type: 'post',
url: "/",
dataType: 'json',
async: true,
cache: false,
data: {
mode: "getkds",
lat: data.response.lat,
lng: data.response.lng
},
success: function (data) {
if (data.response) {
$scope.cityName = data.response.cityName;
$scope.contentString = "<div class='text-center fs-16 py-3'>" + $scope.cityName + " <br>\n" +
"<a ng-click='runfunc();' class='fs-12 text-red font-sfprodisplay-600 btn btn-color3 btn-sm mt-3'>Analyses</a></div>";
$scope.infowindow.setContent($scope.contentString);
$scope.infowindow.open($scope.map, $scope.marker);
if (!$scope.$$phase) $scope.$apply();
}
}
});
}
$scope.runfunc=function(){
alert("123");
}
$scope.init();
}]);

ngMaterial error in Angular app: TypeError: Cannot read property 'confirm' of undefined

I am trying to use ngMaterial in my Angular app and getting the errors: ReferenceError: $event is not defined and TypeError: Cannot read property 'confirm' of undefined. I have looked at the ngMaterial docs and am using the code from this example: https://material.angularjs.org/latest/demo/dialog but can't find what I am doing wrong.
The ReferenceError refers to this line:
$timeout($scope.showConfirm($event), 500);
And the TypeError refers to:
var confirm = $mdDialog.confirm()
Below is my code:
html:
<div style="height: 100%">
<h1>TEST</h1> <!--NOT SHOWING ON PAGE WHICH MEANS THIS IS NOT BEING INVOKED WHEN
URL IS: '/getLocation' like it should-->
<ui-gmap-google-map
class="md-primary md-raised" ng-click="showConfirm($event)"
center='map.center'
zoom='map.zoom'
draggable='map.draggable'
dragging='map.dragging'
refresh='map.refresh'
options='map.options'
events='map.events'
pan='map.pan'>
<ui-gmap-marker
idKey='1'
events='map.events'
coords='map.center'
>
</ui-gmap-marker>
</ui-gmap-google-map>
<script src='//maps.googleapis.com/maps/api/js?key=AIzaSyD4_0KuPivZyV-1EwNGmBCgLc_Z0o8Dyw8'></script>
</div>
Controller:
(function (window, ng) {
ng.module('app', ['uiGmapgoogle-maps', 'ui.router', 'ngMaterial'])
.config(function ($stateProvider) { //had: , $stateChangeError included in the function parameters, but that caused error
$stateProvider.state('getLocation', {
url: '/getLocation',
templateUrl: 'getlocation.html',
controller: 'GetlocationCtrl',
});
})
.controller('GetlocationCtrl', ['$scope', "uiGmapLogger", "uiGmapGoogleMapApi", "$state", "$stateParams", "$timeout",
function ($scope, $log, GoogleMapApi, $state, $stateParams, $timeout, $mdDialog) {
$log.currentLevel = $log.LEVELS.debug;
center = { latitude: 49.22, longitude: -122.66 }; //default center
console.log($stateParams);
$scope.map = {
center: center,
pan: false,
zoom: 16,
refresh: false,
events:
{ click: function newCenter(mapModel, eventName, originalEventArgs)
{
$scope.$apply(function(){
var e = originalEventArgs[0];
$scope.map.center = { latitude: e.latLng.lat(), longitude: e.latLng.lng() };
$timeout($scope.showConfirm($event), 500);
});
}
}
}
$scope.map.circle = {
id: 1,
center: center,
radius: 500, //(current time - date lost)*km/hour
stroke: {
color: '#08B21F',
weight: 2,
opacity: 1
},
fill: {
color: '#08B21F',
opacity: 0.5
},
geodesic: false, // optional: defaults to false
draggable: false, // optional: defaults to false
clickable: true, // optional: defaults to true
editable: false, // optional: defaults to false
visible: true, // optional: defaults to true
events: {
dblclick: function () {
$log.debug("circle dblclick");
},
radius_changed: function (gObject) {
var radius = gObject.getRadius();
$log.debug("circle radius radius_changed " + radius);
}
}
};
$scope.showConfirm = function (ev) {
// Appending dialog to document.body to cover sidenav in docs app
var confirm = $mdDialog.confirm()
.title('Would you like to delete your debt?')
.textContent('All of the banks have agreed to forgive you your debts.')
.ariaLabel('Lucky day')
.targetEvent(ev)
.ok('Please do it!')
.cancel('Sounds like a scam');
$mdDialog.show(confirm).then(function() {
$scope.status = 'You decided to get rid of your debt.';
}, function() {
$scope.status = 'You decided to keep your debt.';
});
};
} ]); //end of controller
//THIS LISTENER DOES NOT DO ANYTHING
// $scope.map.event.addListener(map, 'click', function(event) {
// alert(event.latLng); // in event.latLng you have the coordinates of click
//});
//function confirmLocation() {
// alert('Use this location as {{petName}}\'s last location?')
//}
})(window, angular);
Your controller does not have mdDialog injected, and there is a issue in the way you are injecting, change like below,
controller('GetlocationCtrl', ['$scope', "uiGmapLogger", "uiGmapGoogleMapApi", "$state", "$stateParams", "$timeout","$mdDialog",
function ($scope,uiGmapLogger, uiGmapGoogleMapApi, $state, $stateParams, $timeout, $mdDialog) {

Angular Google Maps Polyline Coordinates from Database

I am trying to display a Polyline on an Ionic application using Angular Google Maps with coordinates from a database. I read the documentation on the Angular Google Maps site regarding getting the coordinates and attempting to create the path via the coordinates from an API. I tried using Angular.forEach to use checklat and checklong as my coordinates but it doesn't show anything on the map. How can I use the coordinates on the data below to display as a polyline?
Data from API:
_id "57393e042613d90300a35a0a"
tripstatus "1"
tripcreated "1463367863236"
tripdescription "testing one two three. i am ironman."
tripname "New trip to test user current trip"
__v 0
checks
0 checklat " 10.72403187357376"
checklong "122.53443290985284"
time "1463367863236"
_id "57394ae62613d90300a35a10"
1 checklat "10.724010661667863"
checklong "122.53442867631733"
time "1463367863236"
_id "57394b272613d90300a35a16"
2 checklat "10.6817828"
checklong "122.5389465"
time "1463367863236"
_id "57394c662613d90300a35a1a"
My Controller:
TripFac.getTrip(id).success(function(data) {
$scope.trips = data;
var latlng = data[0].checks;
angular.forEach(latlng, function(path) {
path = {
latitude: checklat,
longitude: checklong
}
});
$scope.latlng = latlng;
});
//Get Trip Points and put on polyline
$scope.polylines = [];
uiGmapGoogleMapApi.then(function(){
$scope.polylines = [
{
path: latlng,
stroke: {
color: '#6060FB',
weight: 3
},
geodesic: true,
visible: true,
icons: [{
icon: {
path: google.maps.SymbolPath.BACKWARD_OPEN_ARROW
},
offset: '25px',
repeat: '50px'
}]
}
];
});
My view:
<ui-gmap-google-map
center="map.center"
zoom="map.zoom"
id="wrapper">
<style>
.angular-google-map-container { height:450px; width:auto; }
</style>
<ui-gmap-polyline ng-repeat="p in polylines" path="p.path" stroke="p.stroke" visible='p.visible' geodesic='p.geodesic' fit="false" editable="p.editable" draggable="p.draggable" icons='p.icons'></ui-gmap-polyline>
</ui-gmap-google-map>
Foe example
$scope.map.center = {
latitude: $scope.latitude,
longitude: $scope.longitude
};
var directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: true
});
var directionsService = new google.maps.DirectionsService();
$scope.directions = {
origin: new google.maps.LatLng($scope.lat, $scope.lng),
destination: new google.maps.LatLng($scope.latitude, $scope.longitude),
showList: false
}
var request = {
origin: $scope.directions.origin,
destination: $scope.directions.destination,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
directionsDisplay.setMap($scope.map.control.getGMap());
} else {}
});
It could be related with one of the following reasons:
undefined latlng object is passed into $scope.polylines, needs to be changed to $scope.latlng
$scope.polylines could be initialized before json data is getting loaded
The following example demonstrates how to load data from external source and initialize a polygon(s) on the map:
angular.module('map-example', ['uiGmapgoogle-maps'])
.controller('MapController', function($scope, $http, uiGmapGoogleMapApi, uiGmapIsReady) {
$scope.map = {
zoom: 12,
bounds: {},
center: { latitude: 10.6817828, longitude: 122.53443290985284 }
};
var loadPathData = function() {
return $http.get('https://rawgit.com/vgrem/3fc4ffc90de778f38f09b671466001fa/raw/8da45ddf4b174d758892e8a6514fea9145f4b91b/data.json')
.then(function(res) {
//extract data
return res.data[0].checks.map(function(item) {
return {
latitude: item.checklat,
longitude: item.checklong
}
});
});
};
var drawPolylines = function(path) {
$scope.polylines = [
{
path: path,
stroke: {
color: '#6060FB',
weight: 3
},
geodesic: true,
visible: true,
icons: [{
icon: {
path: google.maps.SymbolPath.BACKWARD_OPEN_ARROW
},
offset: '25px',
repeat: '50px'
}]
}
];
}
uiGmapIsReady.promise()
.then(function(instances) {
loadPathData()
.then(drawPolylines);
});
});
.angular-google-map-container {
height: 450px;
width: auto;
}
<div ng-app="map-example" ng-controller="MapController">
<ui-gmap-google-map center="map.center" zoom="map.zoom" id="wrapper">
<ui-gmap-polyline ng-repeat="p in polylines" path="p.path" stroke="p.stroke" visible='p.visible' geodesic='p.geodesic' fit="false"
editable="p.editable" draggable="p.draggable" icons='p.icons'></ui-gmap-polyline>
</ui-gmap-google-map>
<script src="http://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.0.1/lodash.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"></script>
<script src="http://cdn.rawgit.com/nmccready/angular-simple-logger/0.0.1/dist/index.js"></script>
<script src="http://cdn.rawgit.com/angular-ui/angular-google-maps/master/dist/angular-google-maps.min.js"></script>
</div>

Ionic + ngCordova + background geolocation + DeviceReady issue

I'm trying to get the background geolocation plugin to work in my app; however, the page only sometimes loads on my device when I use the deviceready function. From my googling, it seems that I should be using $ionicPlatform.ready instead, but $cordovaBackgroundGeolocation is undefined when I try to do that. Similarly, the device is always undefined when I try to do anything with it.
I also tried manually bootstrapping angular, that didn't work; and I tried simply running the function without putting it inside deviceready or $ionicPlatform.ready or anything; that didn't work either.
The code in question:
Controller:
// Define the angular module
angular.module('testApp.controllers', ['ionic', 'ngCordova.plugins.geolocation', 'ngCordova.plugins.backgroundGeolocation'])
.controller('MapCtrl', ['$scope', '$ionicPopup', '$cordovaGeolocation', '$cordovaBackgroundGeolocation', '$timeout', '$http', '$ionicPlatform',
function ($scope, $ionicPopup, $cordovaGeolocation, $cordovaBackgroundGeolocation, $timeout, $http, $ionicPlatform) {
$scope.loaded = false;
var posOptions = { timeout: 5000, enableHighAccuracy: true, maximumAge: 5000 };
$cordovaGeolocation.getCurrentPosition(posOptions)
.then(function (location) {
$scope.currentLat = location.coords.latitude;
$scope.currentLong = location.coords.longitude;
$scope.loaded = true;
});
$ionicPlatform.ready(function() {
var bgGeo = $cordovaBackgroundGeolocation;
// BackgroundGeoLocation is highly configurable.
bgGeo.configure({
url: 'http://www.my_api_url_here/',
params: {
deviceId: "testApp",
"location": {
"latitude": "38.896339999999995",
"longitude": "-77.08521460000001"
}
},
desiredAccuracy: 10,
stationaryRadius: 20,
distanceFilter: 30,
notificationTitle: 'TestTitle', // <-- android only, customize the title of the notification
notificationText: 'TestText', // <-- android only, customize the text of the notification
activityType: 'OtherNavigation',
debug: true, // <-- enable this hear sounds for background-geolocation life-cycle.
stopOnTerminate: false // <-- enable this to clear background location settings when the app terminates
});
bgGeo.start();
});
}])
Directive:
.directive('bgeo', ['$cordovaGeolocation', '$cordovaBackgroundGeolocation', '$http',
function ($cordovaGeolocation, $cordovaBackgroundGeolocation, $http) {
return {
scope: {
lat: '=',
lng: '='
},
link: function (scope) {
console.log("directive: ", scope.lat, scope.lng);
myLatLng = new google.maps.LatLng(scope.lat, scope.lng);
mapOptions = {
zoom: 16,
center: myLatLng
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
marker = new google.maps.Marker({
position: myLatLng,
map: map,
draggable: false,
icon: 'small-orange-pin.png'
});
}
}
}])
Template:
<ion-scroll zooming="true" direction="xy" style="width:90%">
<div ng-if="loaded" bgeo lat="currentLat" lng="currentLong">
<div id="map" style="width: 600px; height: 500px;"></div>
</div>
</ion-scroll>
app.js run method:
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
if (window.cordova) {
if (window.plugins && window.plugins.backgroundGeoLocation) {
BackgroundGeolocation.configurePlugin(window.plugins.backgroundGeoLocation);
}
}
});
})
The full source code is up on github at https://github.com/sahiltalwar88/binding-geolocation-issue. Any help is much appreciated!
The main issue was that I had to run bower install; I was missing several packages. Once I did that, I could use the ionic ready function and onDeviceReady just fine. Then, in order to get the iOS callback functions working, I had to update my syntax to work with ngCordova (which uses Q and promises) rather than callback functions, as the examples showed.
Here's the structure of my final code:
$ionicPlatform.ready(function() {
if(window.StatusBar) {
StatusBar.styleDefault();
}
$location.path('/app');
$rootScope.$digest();
$rootScope.deviceReady = false;
document.addEventListener('deviceready', function () {
if(window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
window.cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
var bgGeo = $cordovaBackgroundGeolocation;
var deviceId = $cordovaDevice.getUUID();
var addVisitUrl = 'your-url-goes-here';
$rootScope.deviceId = deviceId;
$rootScope.deviceReady = true;
var posOptions = { timeout: 5000, enableHighAccuracy: true, maximumAge: 5000 };
$cordovaGeolocation.getCurrentPosition(posOptions)
.then(function (location) {
$rootScope.currentLat = location.coords.latitude;
$rootScope.currentLong = location.coords.longitude;
var yourAjaxCallback = function(response) {
bgGeo.finish();
};
var callbackFn = function(location) {
var data = {
deviceId: deviceId,
"location": {
"latitude": location.latitude,
"longitude": location.longitude
}
};
$http.post(addVisitUrl, data);
// Other code goes here
yourAjaxCallback.call(this);
};
var failureFn = function(error) {
alert('Background Geolocation Error: ' + error);
// Other code goes here
};
bgGeo.configure({
url: addVisitUrl,
params: {
deviceId: deviceId,
"location": {
"latitude": $rootScope.currentLat,
"longitude": $rootScope.currentLong
}
},
desiredAccuracy: 10,
stationaryRadius: 10,
distanceFilter: 10,
activityType: 'OtherNavigation',
debug: true,
stopOnTerminate: false
})
.then(callbackFn, failureFn, callbackFn);
bgGeo.start();
});
$rootScope.$digest();
});
});
})

angular-google-maps not rendering map, just the map controls

My map is only partially loading the map controls but not rendering the actual map:
I have all of the proper dependencies loaded, using this as a guideline.
my HTML:
<div class="col-xs-3">
<ui-gmap-google-map center="vm.map.center" zoom="vm.map.zoom">
<ui-gmap-layer type="TrafficLayer" show="vm.map.showTraffic"></ui-gmap-layer>
</ui-gmap-google-map>
</div>
I am using the recommended uiGmapGoogleMapApiProvider provider to guarantee that angular-google-maps does not begin processing any directives until all of the Google Maps SDK is fully ready:
angular.module('app', [
'uiGmapgoogle-maps',
]).config(config)
config.$inject = ['uiGmapGoogleMapApiProvider'];
function config(uiGmapGoogleMapApiProvider) {
uiGmapGoogleMapApiProvider.configure({
v: '3.17',
libraries: 'weather,geometry,visualizations'
})
}
And My angular map model inside my controller:
uiGmapGoogleMapApi.then(function(maps) {
console.log(maps, "MAPS");
vm.map = {center: {latitude: 45, logitude: -73}, zoom:8, showTraffic: true, show: true}
})
Why is my map detail not showing up?
Thank you!
added some base options and wa-lah!
uiGmapGoogleMapApi.then(function(maps) {
console.log(maps, "MAPS");
var baseOptions = {
'maxZoom': 15,
'minZoom': 4,
'backgroundColor': '#b0d1d4',
'panControl': false,
'zoomControl': true,
'draggable': true,
'zoomControlOptions': {
'position': 'RIGHT_TOP',
'style': 'SMALL'
}
};
console.log("here")
vm.map = {center: {latitude: 51.219053, longitude: 4.404418}, options:baseOptions, zoom:8, showTraffic: true, show: true}
})

Resources