Only getting a few markers in the map - angularjs

I am very new to angularJS and still exploring.I have created a map and showing around 1500 markers in it but when I load only 11 markers are visible.I am taking the Zip codes from a XML file and using geocoding I am converting them to LatLng and showing in map.Can any one suggest any solution.
Thanks in advance.
//Angular App Module and Controller
var mapApp = angular.module('mapApp', []);
// app.directive("importSheetJs", [SheetJSImportDirective]);
mapApp.factory('mySHaredService', function ($rootScope) {
var mySHaredService = {};
mySHaredService.message = '';
mySHaredService.prepForBroadcast = function (msg) {
this.message = msg;
this.broadcastItem();
};
return mySHaredService;
});
mapApp.controller('MapController', function ($scope, $timeout, $window, $rootScope, mySHaredService) {
//Parsing data from XML
$rootScope.zipArray = [];
var url = "location.xlsx";
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
$rootScope.LatLongList = [{
"latitudeValue": "",
"longitudeValue": ""
}];
oReq.onload = function (e) {
var arraybuffer = oReq.response;
var data = new Uint8Array(arraybuffer);
var arr = new Array();
for (var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
var bstr = arr.join("");
var workbook = XLSX.read(bstr, { type: "binary" });
var first_sheet_name = workbook.SheetNames[0];
var address_of_cell = "K1";
var worksheet = workbook.Sheets[first_sheet_name];
data = JSON.stringify(XLSX.utils.sheet_to_json(worksheet));
console.log("Messege data" + data);
var finalData = JSON.parse(data);
for (var i = 0; i <= finalData.length; i++) {
// console.log("Zip code is " + finalData[i].Zip);
$rootScope.zipArray.push(finalData[i].ZIP);
console.log("Zip code inside zip array is " + $rootScope.zipArray[i]);
}
}
setTimeout(function () {
$scope.$apply(function () {
})
}, 17770);
$timeout(function() {
console.log("Zip data from excel sheet" + $rootScope.zipArray)
var geocoder = new google.maps.Geocoder();
for (var i = 15; i <= $rootScope.zipArray.length; i++) {
var address = $rootScope.zipArray[i];
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
$rootScope.LatLongList.push({
"latitudeValue": latitude,
"longitudeValue": longitude
});
}
});
}
// setTimeout(function () {
// $scope.$apply(function () {
// })
// }, 30000);
$timeout(function () {
console.log("Latitude value " + $rootScope.LatLongList[1].latitudeValue)
var mapOptions = {
zoom: 11,
center: new google.maps.LatLng(33.6496252, -117.9190418),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
$scope.map = new google.maps.Map(document.getElementById('map'), mapOptions);
var circle = new google.maps.Circle({
center: new google.maps.LatLng(33.6496252, -117.9190418),
map: $scope.map,
radius: 10000, // IN METERS.
fillColor: '#FF6600',
fillOpacity: 0.3,
strokeColor: "#FFF",
strokeWeight: 0 // DON'T SHOW CIRCLE BORDER.
});
var bounds = circle.getBounds();
$scope.markers = [];
$rootScope.selectedAd = "";
var selectedLocation = [{ "lat": 0, "long": 0 }];
var infoWindow = new google.maps.InfoWindow();
var createMarker = function (info) {
var marker = new google.maps.Marker({
map: $scope.map,
position: new google.maps.LatLng(info.latitudeValue, info.longitudeValue),
title: ""
});
marker.content = '<div class="infoWindowContent">' + '<br />' + info.latitudeValue + ' E,' + info.longitudeValue + ' N, </div>';
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent('<h2>' + marker.title + '</h2>' +
marker.content);
infoWindow.open($scope.map, marker);
selectedLocation[0].lat = marker.getPosition().lat();
selectedLocation[0].long = marker.getPosition().lng();
console.log("Latitude is " + selectedLocation[0].lat + "Longitude is " + selectedLocation[0].long);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
latLng: marker.getPosition()
}, $scope.selectedLoc = function (responses) {
if (responses && responses.length > 0) {
// alert(responses[0].formatted_address);
$rootScope.selectedAd = responses[0].formatted_address;
setTimeout(function () {
$scope.$apply(function () {
$rootScope.selectedAd = responses[0].formatted_address;
})
}, 1000);
$timeout(function () {
$rootScope.selectedAd = responses[0].formatted_address;
$scope.handleClick = function (msg) {
mySHaredService.prepForBroadcast($rootScope.selectedAd);
}
$scope.$on('handleBroadcast', function () {
$scope.message = $rootScope.selectedAd;
})
}, 2000);
} else {
}
});
});
$scope.markers.push(marker);
}
setTimeout(function () {
}, 3000);
$timeout(function () {
for (i = 1; i < $rootScope.LatLongList.length; i++) {
console.log(bounds.contains(new google.maps.LatLng($rootScope.LatLongList[i].latitudeValue, $rootScope.LatLongList[i].longitudeValue)));
// if (bounds.contains(new google.maps.LatLng($rootScope.LatLongList[i].latitudeValue, $rootScope.LatLongList[i].longitudeValue))) {
createMarker($rootScope.LatLongList[i]);
console.log("The value of i is " + i);
// }
}
}, 4000);
$scope.openInfoWindow = function (e, selectedMarker) {
var data = $rootScope.selectedAd
this.broadcastItem();
window.location = "valuePage.html";
}
}, 4000);
}, 2000);
oReq.send();
});
mapApp.controller("viewApp", function ($scope, $rootScope, mySHaredService, $timeout) {
// $scope.selectedAd = Products.FirstName;
// $scope.selectedAd = Products.FirstName;
setTimeout(function () {
$scope.$on('handleBroadcast', function () {
$scope.message = mySHaredService.message;
});
}, 3000);
$timeout(function () {
$scope.$on('handleBroadcast', function () {
$scope.message = mySHaredService.message;
});
}, 4000);
});

This is because you are sending too many requests through per second.
In addition to daily quota limits, the geocoding service is rate limited to 50 QPS (queries per second), calculated as the sum of client-side and server-side queries.
The Optimizing Quota Usage When Geocoding has a lot of strategies on how to account for that.
In your case I suggest doing a randomized interval for each request you make that way they are spread out you avoid going over the 50 request per second limit.
I've modified the part of your code sample where you are making the request.
mapApp.controller('MapController', function ($scope, $timeout, $window, $rootScope, mySHaredService) {
//Parsing data from XML
$rootScope.zipArray = [];
var url = "location.xlsx";
var randomTime = Math.round(Math.random()*(3000-500))+500;
var geocodeRequest = setTimeout(function() {
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
$rootScope.LatLongList = [{
"latitudeValue": "",
"longitudeValue": ""
}];
oReq.onload = function (e) {
var arraybuffer = oReq.response;
var data = new Uint8Array(arraybuffer);
var arr = new Array();
for (var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
var bstr = arr.join("");
var workbook = XLSX.read(bstr, { type: "binary" });
var first_sheet_name = workbook.SheetNames[0];
var address_of_cell = "K1";
var worksheet = workbook.Sheets[first_sheet_name];
data = JSON.stringify(XLSX.utils.sheet_to_json(worksheet));
console.log("Messege data" + data);
var finalData = JSON.parse(data);
for (var i = 0; i <= finalData.length; i++) {
// console.log("Zip code is " + finalData[i].Zip);
$rootScope.zipArray.push(finalData[i].ZIP);
console.log("Zip code inside zip array is " + $rootScope.zipArray[i]);
}
}
setTimeout(function () {
$scope.$apply(function () {
})
}, 17770);
}, randomTime);

Related

How to merge two different object from JSON data

Hi I need some help with this code snippet. The output that I get is multiple different objects of JSON data. But I want to extract the destination data then merge them as an array. But all the data I get is only one data merge as an array, one by one.
Here is the output:
$scope.findHospital = function(){
$ionicLoading.show({
template: '<ion-spinner icon="bubbles"></ion-spinner><br/>Acquiring location!'
});
var posOptions = {
enableHighAccuracy: true,
timeout: 20000,
maximumAge: 0
};
$cordovaGeolocation.getCurrentPosition(posOptions).then(function (position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
var infowindow;
var myLatlng = new google.maps.LatLng(lat, long);
var mapOptions = {
center: myLatlng,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: myLatlng,
radius: 5000,
type: ['police']
}, callback);
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(lat, long);
geocoder.geocode({'latLng': latlng}, function(results, status) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
var request = { reference: place.reference };
service.getDetails(request, function(details, status) {
console.log(details);
var url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins="+results[0].formatted_address+"&destinations="+details.formatted_address+"&key=AIzaSyDDxMGpu5SP5XwZGrKw5BQWl_r2dgLgpPY";
var distances = [];
$http.get(url).then(function(response){
var str = response.data.rows[0].elements[0].distance.text;
distances = distances.concat(str);
console.log(distances);
});
}
});
}
}
}
CODE UPDATED!
I strongly suspect, distances array is initializing everytime when createMarker method is called. So, put your distances in global scope. i.e. just above your resolving getCurrentPosition promise.
var distances = [];
$cordovaGeolocation.getCurrentPosition(posOptions).then(function (position) {
// your code
and remove distances intialization from inner code.
This is what you need!! A array outside of your function createMarker. When you call $http.get, you should concatenate the response with your distances array.
var distances = []; // HERE
function createMarker(place) {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(lat, long);
geocoder.geocode({'latLng': latlng}, function(results, status) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
var request = { reference: place.reference };
service.getDetails(request, function(details, status) {
var url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins="+results[0].formatted_address+"&destinations="+details.formatted_address+"&key=AIzaSyDDxMGpu5SP5XwZGrKw5BQWl_r2dgLgpPY";
$http.get(url).then(function(response){
var str = response.data.rows[0].elements[0].distance.text;
distances = distances.concat(str); // HERE
});
}
});
}

Incorrect marker location

I am Using the $http Service in Ionic to dynamically load Google Map Markers, and I use this method:
google.maps.Geocode
To give a lat and lang, but this code is throwing some error.
facebookExample.controller('carteController', function ($scope, $ionicLoading, $location, $cordovaGeolocation, $compile, $http) {
$scope.back = function () {
$location.path("/accueil");
}
$scope.init = function () {
$http.get('http://#ip:8080/elodieService/categories/', {
params: {
fields: "nomcategorie,typecategorie",
format: "json"
}
}).then(function (result) {
console.log("SUCCESS!" + result.data);
console.log(JSON.stringify(result));
$scope.categorieData = result.data;
});
var options = {timeout: 10000, enableHighAccuracy: true};
$cordovaGeolocation.getCurrentPosition(options).then(function (position) {
var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
$scope.map = new google.maps.Map(document.getElementById("map"), mapOptions);
google.maps.event.addListenerOnce($scope.map, 'idle', function () {
var marker = new google.maps.Marker({
map: $scope.map,
animation: google.maps.Animation.DROP,
position: latLng
});
$http.get('http://#ip/elodieService/evenements/', {
params: {
fields: "adresse",
format: "json"
}
}).then(function (result) {
console.log("SUCCESS!" + result.data);
console.log(JSON.stringify(result));
$scope.adresseData = result.data;
console.log("result.data: ", result.data.adresse);
var records = result.data;
for (var i = 0; i < records.length; i++) {
var record = records[i];
var adresse = record.adresse;
console.log("adresse obtenu par web service");
console.log(adresse);
var resultat = "";
geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': adresse}, callback);
function callback(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log("results[0].geometry.location");
console.log(results[0].geometry.location.latitude);
lat = results[0].geometry.location.lat();
console.log("lat");
console.log(lat);
lng = results[0].geometry.location.lng();
console.log("lng");
console.log(lng);
console.log(JSON.stringify(results));
var markerPos = new google.maps.LatLng(lat[i], lng[i]);
var marker = new google.maps.Marker({
map: $scope.map,
animation: google.maps.Animation.DROP,
position: markerPos
});
} else {
console.log(status);
}
}
}
});
var infoWindow = new google.maps.InfoWindow({
content: "Here I am!"
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.open($scope.map, marker);
});
console.log(status);
}, function (error) {
console.log("Could not get location");
});
});
}
});
carte.html
<ion-view title="Carte" ng-init="init()">
<ion-content>
<div id="map" data-tap-disabled="true"></div>
</ion-content>
</ion-view>
Error:
incorrect marker location
How can I fix it?
You are passing the incorrect value to LatLng class as lat[i], lng[i]. The index position [i] is invalid.
So change your code like this:
lat = results[0].geometry.location.lat();
console.log("lat");
console.log(lat);
lng = results[0].geometry.location.lng();
console.log("lng");
console.log(lng);
console.log(JSON.stringify(results));
var markerPos = new google.maps.LatLng(lat, lng); // << Fix it here
Even, you don't have to define those lat and lng because you are getting it from a LatLng instance.
if (status == google.maps.GeocoderStatus.OK) {
console.log("results[0].geometry.location", results[0].geometry.location, JSON.stringify(results));
// No need to initialize again as the "results[0].geometry.location" is an instance of LatLng class itself
var markerPos = results[0].geometry.location;
var marker = new google.maps.Marker({
map: $scope.map,
animation: google.maps.Animation.DROP,
position: markerPos
});
}
See Geocoding Results:
results[]: {
types[]: string,
formatted_address: string,
address_components[]: {
short_name: string,
long_name: string,
postcode_localities[]: string,
types[]: string
},
partial_match: boolean,
place_id: string,
postcode_localities[]: string,
geometry: {
location: LatLng,
location_type: GeocoderLocationType
viewport: LatLngBounds,
bounds: LatLngBounds
}
}

Reverse Geocoding AngularJS

I have to improve my code with reverse geocoding. Now my app get the position by device's GPS.
This is my controller:
.controller('MapCtrl', function($scope, $ionicLoading, $compile) {
function initialise() {
function onSuccess(position){
var myLatlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapOptions = {
zoom: 15,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
});
$scope.map = map;
}
function onError(error){
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
google.maps.event.addDomListener(window, 'load', initialise);
});
I found in this link a solution, but I'm not be able to integrate it with my code.
Anyone can help me?
This is the function to get address from lat and long.
$scope.geocoder.geocode({ 'latLng': $scope.latlng }, function (results, status)
And you need to include google api's:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&ver=2014-07-18"></script>
After this you must handle the response.
I post some example code.
$scope.geocoder.geocode({ 'latLng': $scope.latlng }, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[1]) {
$scope.address = results[1].address_components;
$scope.gps_data.address = $scope.address;
//your code here
// some example results parsing code
var i;
$scope.comune = undefined;
for (i = 0; i < $scope.gps_data.address.length; i += 1) {
if ($scope.gps_data.address[i].types.indexOf("administrative_area_level_3") > -1) {
$scope.comune = $scope.gps_data.address[i].short_name;
console.log($scope.comune);
}
}
if ($scope.comune === undefined) {
for (i = 0; i < $scope.gps_data.address.length; i += 1) {
if ($scope.gps_data.address[i].types.indexOf("locality") > -1) {
$scope.comune = $scope.gps_data.address[i].short_name;
}
}
}
} else {
console.log('Location not found');
$scope.firstExecution = false;
}
} else {
console.log('Geocoder failed due to: ' + status);
$scope.firstExecution = false;
}
});
Anyway, you need to check this documentation for better knwoledgment
https://developers.google.com/maps/documentation/javascript/examples/geocoding-reverse
Here you can find all the tags about the object structure that you recieve from google's api.

angular, try to display object in ng-repeat fails

i'm writing an mobile application in javascript with angularJS and ionicframework (last beta v.11), i create dinamically an object and want to display all objects inside in a ng-repeat. Why nr-repeat don't display anything?
This is screen from my object:
I use this code for put values in scope:
$scope.distanceSuppliers = myCar;
And this is the code in html:
<ion-item ng-repeat="(id, supplier) in distanceSuppliers">
<div class="items item-button-right" ng-click="openDetails(id)">
{{supplier.name}}<br />
{{supplier.address}}<br />
</div>
</ion-item>
This is my complete code for JS:
.controller('suppliers', function($scope, cw_db, $ionicPopup, $ionicActionSheet, appdelegate, $rootScope, $firebase, $location, $ionicLoading, cw_position) {
$ionicLoading.show({
template: 'Updating data..'
});
var geocoder;
var tot = 0;
var done = 0;
geocoder = new google.maps.Geocoder();
cw_db.getData(cw_db.getSuppliers(), "", function(suppliers) {
cw_position.getPosition(function (error, position) {
suppliers.on('value', function(supp) {
$scope.distanceSuppliers = {};
tot = 0;
done = 0;
supp.forEach(function(childSnapshot) {
tot++;
var childData = childSnapshot.val();
if (childData.address) {
calculateDistance(childData, position.coords.latitude, position.coords.longitude);
}
});
});
$ionicLoading.hide();
});
});
function calculateDistance(childData, usrLat, usrLon) {
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [new google.maps.LatLng(usrLat, usrLon)],
destinations: [childData.address],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
done++;
var results = response.rows[0].elements;
childData.distance = results[0].distance.value;
$scope.distanceSuppliers.push(childData);
if (done == tot) {
console.log($scope.distanceSuppliers);
}
}
});
}
$scope.openDetails = function(index) {
//appdelegate.setCallId(index);
//$location.path("/app/supplierDetails");
}
})
what's wrong?
Not sure, but I believe you have a data binding update problem.
Try using the $timeout to force the render:
w_position.getPosition(function (error, position) {
$timeout(function() {
suppliers.on('value', function(supp) {
$scope.distanceSuppliers = {};
tot = 0;
done = 0;
supp.forEach(function(childSnapshot) {
tot++;
var childData = childSnapshot.val();
if (childData.address) {
calculateDistance(childData, position.coords.latitude, position.coords.longitude);
}
});
});
$ionicLoading.hide();
});
});
And don't forget to add the $timeout parameter to the controller:
.controller('suppliers', function($scope, ...<other parameters here>..., $timeout) {
I found the problem! Fix using $scope.$apply();
The problem was that i was writing in a different $scope using this code:
cw_position.getPosition(function (error, position) {
suppliers.on('value', function(supp) {
tot = 0;
done = 0;
supp.forEach(function(childSnapshot) {
tot++;
var childData = childSnapshot.val();
if (childData.address) {
calculateDistance(childData, position.coords.latitude, position.coords.longitude);
}
});
});
$ionicLoading.hide();
});
where cw_position.getPosition call a js with this code:
angular.module('cw_position', [])
.service('cw_position', function() {
this.getPosition = function(callback) {
navigator.geolocation.getCurrentPosition(
function (position) {
return callback(null, position);
},
function(error) {
return callback(error, null);
}
);
}
// Built google maps map option
//
this.getGoogleMapOptions = function (lat, lon, zoom, type) {
if (type == null) {
type = google.maps.MapTypeId.ROADMAP;
}
var mapOptions = {
center: new google.maps.LatLng(lat, lon),
zoom: zoom,
mapTypeId: type
};
return mapOptions;
}
});
navigator.geolocation.getCurrentPosition causes the 'problem'
Thx to all for your help

AngularJs: Priorities controlles calls in angularJs

I am facing problem on angularJs calendar. Basically I am using Angular-UI calendar So I have created a controller called "CalendarController" in this controller I am calling service and getting data using ajax call... but I don't know why its happening, When page is loading it goes into directly calendar config line and then it goes for the service ajax call. So can anyone have some solution for this.
Goal: Need to priorities the controller calls e.g. if I have 2 controllers Ctrl1 and Ctrl2, then if I want call Ctrl2 and after then Ctrl1 will call.
'use strict';
/* Controllers */
angular.module('myApp', ['myApp.services','myApp.directives','myApp.filters','ui.bootstrap', '$strap.directives']).
controller('navCtrl', function($scope) {
console.log("### navController");
}).
controller('ContactController', function($scope, contactFactory) {
console.log("### ContactController is called");
/**
* Getting Contact detail
**/
$scope.contacts = [];
contactFactory.getContacts().success(function(response){
$scope.contacts = response.data;
console.log("### Getting Contact data");
console.log($scope.contacts);
});
}).
controller('ActivityController', function($scope, activityFactory) {
$scope.oneAtATime = true;
$scope.loading = true;
activityFactory.getNotifications().success(function(response){
var activityData = [];
var total = parseInt(response.data.length);
for (var i=0; i<total; i++)
activityData.push(response.data[i].desc);
$scope.activities = activityData;
console.log("### Getting Activity data");
console.log($scope.activities);
$scope.loading = false;
});
}).
controller('CalendarController', function($scope, contactFactory, calendarFactory) {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
/* event source that pulls from google.com */
$scope.eventSource = {
editable: true,
className: 'gcal-event', // an option!
currentTimezone: 'America/Chicago' // an option!
};
/* event source that contains custom events on the scope */
/**
* Getting Staff detail
**/
$scope.staff = [];
var staffDetail = {};
contactFactory.getStaff().success(function(response){
var staffData = response.data;
if(staffData!=null) {
var total = parseInt(staffData.length);
for (var i=0; i<total; i++) {
staffDetail = {
'id': staffData[i].staffId,
'name': staffData[i].name,
};
$scope.staff.push(staffDetail);
}
}
console.log("### Getting Staff data");
console.log($scope.staff);
});
var calDailyEvents = {};
$scope.events = [];
calendarFactory.getCalendarDailyEvents().success(function(response){
var eventData = response.data;
console.log("### getCalendarDailyEvents");
if(eventData!=null) {
var total = parseInt(eventData.length);
for (var i=0; i<total; i++) {
var totalStaff = eventData[i].eventAssignedToForms.length;
var staffIds = [];
for(var j=0;j<totalStaff;j++) {
staffIds.push(eventData[i].eventAssignedToForms[j].contactId);
}
console.log(staffIds);
calDailyEvents = {
'id': eventData[i].id,
'title': eventData[i].eventName,
'start': Date(eventData[i].startDate),
allDay: false,
resource: staffIds
};
$scope.events.push(calDailyEvents);
}
}
console.log("### Getting DailyEvents data");
console.log($scope.events);
});
/* event source that calls a function on every view switch */
$scope.eventsF = function (start, end, callback) {
/*Commented for testing purpose*/
/* var s = new Date(start).getTime() / 1000;
var e = new Date(end).getTime() / 1000;
var m = new Date(start).getMonth();
var events = [{title: 'Feed Me ' + m,start: s + (50000),end: s + (100000),allDay: false, className: ['customFeed']}];
callback(events); */
};
/* alert on eventClick */
$scope.alertEventOnClick = function( calEvent, jsEvent, view ){
$scope.$apply(function(){
$scope.alertMessage = ('Event: ' + calEvent.title);
$scope.alertMessage += ('View: ' + view.name);
});
};
$scope.onEventRender = function(event, element) {
console.log("### onEventRender");
};
$scope.onDayClick = function( date, allDay, jsEvent, view ){
$scope.$apply(function(){
$scope.alertMessage = ('Day Clicked ' + date);
});
//$scope.$popover();
};
/* alert on Drop */
$scope.alertOnDrop = function(event, dayDelta, minuteDelta, allDay, revertFunc, jsEvent, ui, view){
$scope.$apply(function(){
$scope.alertMessage = ('Event Droped to make dayDelta ' + dayDelta);
});
};
/* alert on Resize */
$scope.alertOnResize = function(event, dayDelta, minuteDelta, revertFunc, jsEvent, ui, view ){
$scope.$apply(function(){
$scope.alertMessage = ('Event Resized to make dayDelta ' + minuteDelta);
});
};
/* add and removes an event source of choice */
$scope.addRemoveEventSource = function(sources,source) {
var canAdd = 0;
angular.forEach(sources,function(value, key){
if(sources[key] === source){
sources.splice(key,1);
canAdd = 1;
}
});
if(canAdd === 0){
sources.push(source);
}
};
/* add custom event*/
$scope.addEvent = function() {
$scope.events.push({
title: 'Open Sesame',
start: new Date(y, m, 28),
end: new Date(y, m, 29),
className: ['openSesame']
});
};
/* remove event */
$scope.remove = function(index) {
$scope.events.splice(index,1);
};
/* Change View */
$scope.changeView = function(view) {
$scope.myCalendar.fullCalendar('changeView',view);
};
/* config object */
$scope.uiConfig = {
calendar:{
height: 450,
editable: true,
header:{
left: 'prev,next',
center: 'title',
right: 'resourceDay, agendaWeek, resourceWeek',
},
resources: $scope.contacts,
allDaySlot: false,
defaultView: 'resourceDay',
dayClick: $scope.onDayClick,
eventClick: $scope.alertEventOnClick,
eventDrop: $scope.alertOnDrop,
eventResize: $scope.alertOnResize,
eventRender: $scope.onEventRender
}
};
console.log($scope.contacts);
/* event sources array*/
$scope.eventSources = [$scope.events, $scope.eventSource, $scope.eventsF];
});

Resources