• Tidak ada hasil yang ditemukan

Penyelesaian Travelling Salesman Problem Dengan Algoritma Simulated Annealing Studi Kasus: Technical Support BTSSoft

N/A
N/A
Protected

Academic year: 2017

Membagikan "Penyelesaian Travelling Salesman Problem Dengan Algoritma Simulated Annealing Studi Kasus: Technical Support BTSSoft"

Copied!
39
0
0

Teks penuh

(1)

Nama

: Leonardo Davinsi Nainggolan

Tempat/ Tanggal Lahir : Tarutung, 11 Mei 1992

Alamat

: Jl. Harmonika Gg.Flamboyan No.35 A Tanjung Sari

Jenis Kelamin

: Laki-laki

Agama

: Kristen Protestan

Tinggi

: 170 cm

No. Telp/Hp

: 081377224211

Status

: Belum kawin

Email

:

[email protected]

PENDIDIKAN FORMAL

Universitas Sumatera Utara D3 Teknik Informatika Fakultas MIPA Medan. (Tahun

Ajaran 2010 s/d 2013. Berijazah).

Sekolah Menengah Atas Negeri 2 Tarutung. ( Tahun Ajaran 2007 s/d 2010.

Berijazah).

Sekolah Menengah Pertama Negeri 2 Tarutung. (Tahun Ajaran 2004 s/d 2007.

Berijazah).

Sekolah Dasar Negeri 5 Tautung. (Tahun Ajaran 1998 s/d 2004. Berijazah).

SEMINAR

Peserta Seminar Nasional Literasi Informasi 2014 Universitas Sumatera Utara.

PENGALAMAN KERJA

Magang di Biro Pembangunan PLN Medan Tahun 2012.

Technical Support, Programmer di BTSSoft Medan Sejak Tahun 2013

DATA KEMAMPUAN

Database : SQL server, Mysql, Firebase, MongoDB dan Microsoft Access.

Desain : Adobe Photoshop, CorelDraw, Adobe Flash, Pinnacle.

(2)

LISTING PROGRAM

1.

Sisi Klien (

mobile android

)

1.1

js/app.js

1.

2. angular.module('starter', ['ionic', 'ngCordova', 'angularMoment', 'firebase', 'starter.controllers', 'starter.directives'])

3.

4. .run(function($window, $document, $ionicLoading, $state, $ionicPlatform, $log, $rootScope, $cordovaClipboard, GoogleMaps) {

5. $ionicPlatform.ready(function() { 6. $log.log("Ionic ready");

7.

8. if (window.cordova && window.cordova.plugins.Keyboard) { 9. cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); 10. cordova.plugins.Keyboard.disableScroll(true);

11.

12. }

13. if (window.StatusBar) { 14. StatusBar.styleDefault(); 15. }

16.

17. GoogleMaps.cekTanggal();

18. if($rootScope.kunjungan=='undefined') 19. $rootScope.kunjungan = [];

20.

21. $rootScope.markersKunjungan = []; 22.

23. }); 24.

25. 26.}) 27.

28..config(function($stateProvider, $urlRouterProvider) { 29. $stateProvider

30.

31. .state('app', { 32. url: '/app', 33. abstract: true,

34. templateUrl: 'templates/menu.html', 35. controller: 'AppCtrl'

36. }) 37.

38. .state('app.maps', { 39. url: '/maps', 40. views: {

41. 'menuContent': {

42. templateUrl: 'templates/maps.html', 43. controller: 'MapCtrl'

44. } 45. } 46. }) 47.

48. .state('app.pelanggan', { 49. url: '/pelanggan', 50. views: {

51. 'menuContent': {

52. templateUrl: 'templates/pelanggan.html', 53. controller: 'PelangganCtrl'

(3)

58. .state('app.kunjungan', { 59. url: '/kunjungan', 60. views: {

61. 'menuContent': {

62. templateUrl: 'templates/kunjungan.html', 63. controller: 'KunjunganCtrl'

64. } 65. } 66. }) 67.

68. .state('app.result', { 69. url: '/result', 70. views: {

71. 'menuContent': {

72. templateUrl: 'templates/result.html', 73. controller: 'ResultCtrl'

74. } 75. } 76. }) 77.

78. .state('app.matrix_data', { 79. url: '/matrix_data', 80. views: {

81. 'menuContent': {

82. templateUrl: 'templates/matrix_data.html', 83. controller: 'matrix_dataCtrl'

84. } 85. } 86. }) 87.

88. .state('app.editKoordinat', { 89. url: '/editKoordinat/:aId', 90. views: {

91. 'menuContent': {

92. templateUrl: 'templates/editKoordinat.html', 93. controller: 'editKoordinatCtrl'

94. } 95. } 96. 97. }) 98.

99. .state('app.editKunjungan', { 100. url: '/edit_kunjungan', 101. views: {

102. 'menuContent': {

103. templateUrl: 'templates/editKunjungan.html', 104. controller: 'editKunjunganCtrl'

105. } 106. } 107. 108. 109. }) 110.

111.

112. .state('login', { 113. url: '/login',

114. templateUrl: 'templates/login.html', 115. controller: 'loginCtrl'

116. }) 117.

118. .state('app.pengaturan', { 119. url: '/pengaturan', 120. views: {

121. 'menuContent': {

122. templateUrl: 'templates/pengaturan.html', 123. controller: 'PengaturanCtrl'

(4)

125. } 126. }) 127.

128. .state('app.tentang', { 129. url: '/tentang', 130. views: {

131. 'menuContent': {

132. templateUrl: 'templates/tentang.html' 133. }

134. } 135. }); 136.

137.

138. $urlRouterProvider.otherwise('/app/maps'); 139. })

140.

141. .factory('ModifyRootScopeService', function($rootScope){ 142.

143. return {

144. setRootScopeValue: function(value){ 145. $rootScope.map = value;

146. } 147. } 148. }) 149.

150. .factory('ConnectivityMonitor', function($rootScope, $cordovaNetwork){ 151.

152. return {

153. isOnline: function(){ 154.

155. if(ionic.Platform.isWebView()){

156. return $cordovaNetwork.isOnline(); 157. } else {

158. return navigator.onLine; 159. }

160.

161. },

162. ifOffline: function(){ 163.

164. if(ionic.Platform.isWebView()){

165. return !$cordovaNetwork.isOnline(); 166. } else {

167. return !navigator.onLine; 168. }

169.

170. } 171. } 172. }); 173. 174. 175. 176.

177. <iinfinite-scroll icon="iloading-c" on-infinite="loadMoreCustomer($scope.settings.connection)">

178. </ioninfinitescroll><! ngif="moreDataCanBeLoaded()" -->

179. 180. </div> 181.

182. </ion-content> 183. </ion-view>

1.2

js/controllers.js

(5)

2.

3. .controller('AppCtrl', function($scope, $ionicModal, $timeout, $location, $window, $rootScope, $http, $ionicLoading, $ionicPopup,

$ionicActionSheet, $state, $cordovaClipboard, $ionicHistory, KunjunganStorage, GoogleMaps) {

4. //define variable

5. $rootScope.settings = []; 6.

7.

8. //define firebase setting

9. $rootScope.ref = new Firebase("https://glowing-torch-4411.firebaseio.com/web/maps");

10.

11. /* settings */

12. var dataSettings = localStorage['settings']; 13. $scope.settingsObject =

{"connection":"tspsa.btssoft.com","avoid_highaway":false,"avoid_toll_road s":true,"optimizewaypoint":false,"travel_mode":"WALKING","interval":10000 , "tracker":true,"mTemp":20,"mItr":3,"mSukses":5,"decT":0.95};

14. //define default settings

15. if (dataSettings === undefined || dataSettings == ''){ 16. //var settingsObject =

{"connection":"tspsa.btssoft.com","avoid_highaway":false,"avoid_toll_road s":true,"optimizewaypoint":false,"travel_mode":"WALKING"};

17. localStorage.setItem('settings', JSON.stringify($scope.settingsObject));

18. $rootScope.settings = JSON.parse(localStorage.getItem('settings')); 19. console.log("set settings");

20. } 21.

22. //get settings

23. if(dataSettings !== undefined && dataSettings != ''){ 24. console.log(dataSettings);

25. $rootScope.settings = JSON.parse(localStorage.getItem('settings')); 26. }

27.

28. //-- data user

29. var userData = localStorage['user'];

30. if(userData !== undefined && userData != ''){ 31. $rootScope.user = JSON.parse(userData); 32. }

33.

34. /* main app management */ 35. //-- logout

36. $scope.logOut = function () { 37. console.log("Logout"); 38. localStorage.login="false"; 39. localStorage.email="";

40. window.location.href = "login.html"; 41. };

42.

43. /* END OF MAIN APP Management */ 44.

45. /* Kunjungan Management */

46. $scope.moveItem = function(item, fromIndex, toIndex) { 47. //Move the item in the array

48. console.log(item);

49. console.log("from : " + fromIndex); 50. console.log("to : " + toIndex);

51. $rootScope.kunjungan.splice(fromIndex, 1); 52. $rootScope.kunjungan.splice(toIndex, 0, item); 53. };

54.

55. $scope.onItemDelete = function(item){ 56.

57. date = new moment();

(6)

59. console.log(item.kode); 60.

61. $http.get("http://"+$rootScope.settings.connection + "/api/kunjungan.php?act=delete&pelanggan="+ item.kode +

"&technical="+$rootScope.user.reg_id+"&tanggal="+current_date) 62. .then(function(response){

63.

64. console.log(response);

65. alert("Sukses dihapus dari daftar kunjungan!"); 66.

67. if ($rootScope.markersKunjungan!=undefined || $rootScope.markersKunjungan!=""){

68. remove_markerLocation(); 69. }

70.

71. GoogleMaps.reloadMarkers(); 72. },

73. function(error){ 74. console.log(error);

75. alert("Gagal Hapus, error: \n +" + error.message); 76. });

77. 78. }; 79.

80. function remove_markerLocation(){ 81.

82. if($rootScope.markersKunjungan !== undefined && $rootScope.markersKunjungan.length > 0){

83. for (var i=0; i<$rootScope.markersKunjungan.length; i++) { 84. $rootScope.markersKunjungan[i].setMap(null);

85. } 86. } 87.

88. } 89.

90. $rootScope.addLocation=function(pelanggan, technical){

91. var data="act=add&pelanggan="+pelanggan+"&technical="+technical; 92. $http.get("http://"+$rootScope.settings.connection +

"/api/kunjungan.php?"+data) 93. .then(function(response){

94. if (response.data.success == true){ 95. console.log(response);

96.

97. if ($rootScope.markersKunjungan!=undefined || $rootScope.markersKunjungan!=""){

98. remove_markerLocation(); 99. }

100.

101. GoogleMaps.reloadMarkers(); 102.

103. alert(response.data.customers[pelanggan].nama + " berhasil ditambahkan ke kunjungan!");

104. } else {

105. alert("Anda sudah memasukkan sebagai kunjungan anda!"); 106. }

107.

108. },

109. function(error){ 110. console.log(error);

111. //$rootScope.customers = error; 112. });

113. }; 114.

115. function saveHasiltoLocalStorage(data, data_ls){ 116.

(7)

119.

120. $scope.loadingHitung = function(){ 121. $ionicLoading.show({

122. content: 'Sedang menghitung...', 123. showBackdrop: false

124. }); 125. }; 126.

127. $scope.hide = function(){

128. $ionicLoading.hide().then(function(){

129. console.log("The loading indicator is now hidden"); 130. });

131. }; 132.

133. function AddRoute(route){ 134. GoogleMaps.AddRoute(route); 135. }

136.

137. $scope.hitung = function(){

138. if ($rootScope.markersKunjungan==undefined || $rootScope.markersKunjungan==""){

139. alert("Anda belum memasukkan daftar kunjungan!"); 140. } else {

141.

142. $rootScope.tspsa = [];

143. KunjunganStorage.Calculate_TSPSA().then(function(response){ 144. $rootScope.daftarKunjungan = $rootScope.kunjungan;

145. $scope.loadingHitung;

146. if (response.data.success = true){ 147. $rootScope.tspsa = response.data;

148. console.log("Success get optimation TSP from server"); 149. console.log($rootScope.tspsa);

150.

151. saveHasiltoLocalStorage(JSON.stringify($rootScope.tspsa), 'tsp_sa');

152.

153. cekVariable(); 154.

155. if ($rootScope.directionsService==undefined) 156. GoogleMaps.clearDirections();

157. GoogleMaps.AddRoute($rootScope.tspsa.rute_sa); 158. }else{

159. alert("Error : "+response.data.error_message); 160. console.log("Error : "+response.data.error_message); 161. }

162. },

163. function (error) {

164. console.log("Error : "+ error); 165. $scope.hide();

166. }); 167. }

168. 169. }; 170.

171. function checkNested(obj /*, level1, level2, ... levelN*/) { 172. var args = Array.prototype.slice.call(arguments, 1);

173.

174. for (var i = 0; i < args.length; i++) { 175. if (!obj || !obj.hasOwnProperty(args[i])) { 176. return false;

177. }

178. obj = obj[args[i]]; 179. }

180. return true; 181. }

182.

(8)

184. $scope.showConfirmLogout = function() { 185. var confirmPopup = $ionicPopup.confirm({ 186. title: 'Logout',

187. template: 'Apakah anda yakin ingin keluar?' 188. });

189.

190. confirmPopup.then(function(res) { 191. if(res) {

192. $scope.logOut()

193. console.log('You are log out.'); 194. lo

195. } else {

196. console.log('You are not sure'); 197. }

198. }); 199. }; 200.

201. $rootScope.setCenterUser = function(lat, lng){ 202. var myLatLng = new google.maps.LatLng(lat, lng); 203. $rootScope.map.setCenter(myLatLng);

204. }; 205.

206. $rootScope.setCenterUserGo = function(lat, lng){ 207. $rootScope.setCenterUser(lat, lng);

208. alert("Peta sudah di set center " + lat + ', ' + lng); 209. //$location.path('/app/maps');

210. $state.transitionTo("/app/maps"); 211. };

212.

213. function cekVariable(){

214. if ($rootScope.tspsa == undefined || $rootScope.tspsa ==''){ 215. KunjunganStorage.getLocalstorage("tsp_sa")

216. .then(function(response){ 217. $rootScope.tspsa = response;

218. console.log("sukses mendapatkan nilai TSPSA dari localStorage.");

219. }, 220.

221. function (error) {

222. console.log("error get TSPSA from localstorage: " + error); 223. });

224.

225. } 226.

227. if ($rootScope.daftarKunjungan == undefined || $rootScope.daftarKunjungan ==''){

228. KunjunganStorage.getLocalstorage("kunjungan") 229. .then(function(response){

230. $rootScope.daftarKunjungan = response;

231. console.log("sukses mendapatkan nilai daftarKunjungan dari localStorage.");

232. }, 233.

234. function (error) {

235. console.log("error get daftarKunjungan from localstorage: " + error);

236. }); 237.

238. } 239.

240. console.log($rootScope.rute_sa);

241. console.log($rootScope.daftarKunjungan); 242. }

243.

244. // Triggered on a button click, or some other target 245. $rootScope.more = function() {

(9)

247. // Show the action sheet

248. var hideSheet = $ionicActionSheet.show({ 249. buttons: [

250. { text: 'Set center BTSSOFT' }, 251. { text: 'Hide Marker' },

252. { text: 'Reload Marker' }, 253. { text: 'Hide Route' }, 254. { text: 'Reload Route' }, 255. { text: 'Reload Page' }, 256. { text: 'Result'}, 257. ],

258. /*destructiveText: 'Delete',*/ 259. titleText: 'More Action', 260. cancelText: 'Cancel', 261. cancel: function() { 262. // add cancel code.. 263. },

264. buttonClicked: function(index) { 265. if (index == 0){

266. $rootScope.setCenterUser( 3.623004, 98.676711); 267. hideSheet();

268. }

269. if (index == 1){ 270.

271. remove_markerLocation(); 272.

273. hideSheet(); 274. }

275. if (index == 2){

276. GoogleMaps.reloadMarkers(); 277. hideSheet();

278. }

279. if (index == 4){ 280. //cekVariable();

281. if ($rootScope.directionsService==undefined) 282. GoogleMaps.clearDirections();

283. if ($rootScope.tspsa !== undefined){

284. GoogleMaps.AddRoute($rootScope.tspsa.rute_sa); 285. }else{

286. GoogleMaps.clearDirections(); 287. cekVariable();

288. KunjunganStorage.getLocalstorage("tsp_sa") 289. .then(function(response){

290. $rootScope.tspsa = response;

291. GoogleMaps.AddRoute(response.rute_sa);

292. console.log("sukses mendapatkan nilai TSPSA dari localStorage.");

293. }, 294.

295. function (error) {

296. alert("Anda belum pernah menghitung route"); 297. console.log("error find route " +error); 298. });

299. 300. }

301. hideSheet(); 302. }

303. if (index == 3){

304. GoogleMaps.clearDirections(); 305. hideSheet();

306. }

307. if (index == 5){ 308. hideSheet();

309. //$state.go($state.current, {}, {reload: true}); 310. $window.location.reload(true)

311.

(10)

313. if (index == 6){ 314. hideSheet();

315. window.location.href = "#/app/result"; 316. }

317.

318. } 319. }); 320.

321. $timeout(function() { 322. hideSheet();

323. }, 10000); 324.

325. }; 326.

327. $scope.setDirection=function(route){ 328. cekVariable();

329. if ($rootScope.directionsService==undefined) 330. GoogleMaps.clearDirections();

331. GoogleMaps.AddRoute(route);

332. alert("set directionsService : "+route); 333. $ionicHistory.nextViewOptions({

334. disableBack: true 335. });

336.

337. $state.go('app.maps'); 338. };

339. 340. }) 341. 342.

343. .controller('MapCtrl', function($scope, $state, $cordovaGeolocation, $ionicLoading, $firebase, $ionicPopup, $rootScope,

$cordovaBackgroundGeolocation, $interval, $ionicActionSheet, $timeout, moment, GoogleMaps) {

344. GoogleMaps.init("AIzaSyC3kP8F6zHr8rt4J-_MVTdfwtp28VjbVMg"); 345. document.addEventListener('deviceready', function () {

346.

347. alert("masuk ke device ready");

348. cordova.plugins.backgroundMode.setDefaults({ 349. title: 'TSPSA',

350. text: 'Background geolocation' 351. });

352.

353. // Enable background mode

354. cordova.plugins.backgroundMode.enable(); 355.

356. $cordovaBackgroundGeolocation.configure(options) 357. .then(

358. null, // Background never resolves 359. function (err) { // error callback

360. alert("plugin background geolocation tidak aktif@"); 361. },

362. function (location) { // notify callback 363. alert("suskes beackground geolocation!"); 364. console.log(location);

365. setInterval(function () { 366. alert("kirim data");

367. GoogleMaps.centermeLocation($rootScope.ref, $rootScope.user.username, $rootScope.user.pict, location); 368.

369. }, $rootScope.settings.interval); 370.

371. }); 372. }, false); 373.

(11)

376. $scope.hide = function () { 377. alert("test");

378. $ionicLoading.hide(); 379.

380. }; 381.

382. var options = {timeout: 10000, enableHighAccuracy: true}; 383.

384. $scope.mapCreated = function(map) { 385. $scope.map = map;

386. }; 387.

388. $scope.centerOnMe = function () {

389. console.log("ref : " + $rootScope.ref);

390. console.log("username : " + $rootScope.user.username);

391. GoogleMaps.centerMe($rootScope.ref, $rootScope.user.username, $rootScope.user.pict);

392. //GoogleMaps.cekMarker(); 393.

394. }; 395.

396. // cek geolocation

397. function watchGeocodePosition(){

398. console.log("watchGeocodePosition() starting"); 399. }

400.

401. $scope.toggleBounce = function() { 402. if (marker.getAnimation() !== null) { 403. marker.setAnimation(null);

404. } else {

405. marker.setAnimation(google.maps.Animation.BOUNCE); 406. }

407. }; 408.

409.

410. //tracker for firebase

411. $scope.sendLocation = function(){ 412. GoogleMaps.sendLocation(); 413. };

414.

415. $scope.clearMarkers = function(){ 416. GoogleMaps.clearMarkersMap(); 417. }

418.

419. $scope.tracker = function () { 420.

421.

422. if($rootScope.settings.tracker == false) { 423. $rootScope.settings.tracker = true; 424. setintervalTracker();

425. } 426. else

427. $rootScope.settings.tracker = false; 428.

429. console.log("isi tracker = " + $rootScope.settings.tracker); 430. cektrackName();

431. }; 432.

433. function cektrackName() {

434. if($rootScope.settings.tracker == false) { 435. $scope.TrackName = 'Watch Now';

436. $scope.TrackIcon = 'ion-ios-navigate'; 437. }

438. else{

(12)

442. } 443.

444. function setintervalTracker(){

445. if ($rootScope.settings.tracker==true){ 446. // update location withsetting interval 447. interval =

setInterval(updateMarker,$rootScope.settings.interval); 448.

449. } 450. } 451.

452. //setintervalTracker(); 453. cektrackName();

454.

455. function updateMarker() {

456. console.log("set interval namanya ini men!!"); 457. $scope.centerOnMe();

458.

459. // cek setting tracker

460. if($rootScope.settings.tracker == false) { 461. clearInterval(interval);

462. } 463. } 464. 465. }) 466.

467. .controller('PengaturanCtrl', function($scope, $rootScope) { 468. console.log("Pengaturan : "+localStorage.getItem('settings')) ; 469.

470. $scope.toggleChange = function(){ 471. console.log('Toggle changed!'); 472. };

473.

474. $scope.cekScopeSettings = function(){ 475. console.log($rootScope.settings); 476. alert($rootScope.settings); 477. };

478.

479. $scope.saveSettings = function(){ 480. localStorage.setItem('settings',

JSON.stringify($rootScope.settings)); 481. console.log($rootScope.settings); 482. alert("Settings diperbaharui!"); 483. };

484.

485. $scope.setupDefaultSetting = function(){ 486. alert("Setup to default settings!"); 487. localStorage.setItem('settings',

JSON.stringify($scope.settingsObject)); 488. $rootScope.settings =

JSON.parse(localStorage.getItem('settings')); 489. console.log("set settings");

490. } 491. 492. }) 493.

494. .controller('PelangganCtrl', function($scope, $http, moment, $window, $location, $rootScope, $state){

495. if ($rootScope.customers == undefined) 496. $rootScope.customers = [];

497.

498. $scope_pelanggan_selected = $state.params.aId; 499.

500. $http.get("http://"+$rootScope.settings.connection + "/api/customers.php?act=view")

501. .then(function(response){

(13)

503.

504. console.log($rootScope.customers); 505.

506. $rootScope.server_error = checkNested(response, 'data', 'customers');

507.

508. },

509. function(error){ 510. console.log(error);

511. $rootScope.customers = error; 512. });

513.

514. function checkNested(obj /*, level1, level2, ... levelN*/) { 515. var args = Array.prototype.slice.call(arguments, 1); 516.

517. for (var i = 0; i < args.length; i++) { 518. if (!obj || !obj.hasOwnProperty(args[i])) { 519. return false;

520. }

521. obj = obj[args[i]]; 522. }

523. return true; 524. }

525.

526. $scope.strip = function(html) 527. {

528. var tmp = document.createElement("DIV"); 529. tmp.innerHTML = html;

530. return tmp.textContent || tmp.innerText || ""; 531. };

532. 533. 534.

535. $scope.$on('$stateChangeSuccess', function() { 536. $scope.loadMoreCustomer();

537. }); 538.

539. $scope.editKoordinat = function(customer_edit, $location, $window) { 540.

541. $rootScope.customerEdit = customer_edit; 542. window.location.href = '#/app/editKoordinat'; 543. };

544. 545. }) 546.

547. .controller('KunjunganCtrl', function($scope, $http, moment, $rootScope, KunjunganStorage) {

548. 549. 550. }) 551.

552. .controller('ResultCtrl', function($scope, $rootScope, $cordovaClipboard, $ionicHistory, $state, KunjunganStorage) { 553.

554. if ($rootScope.tspsa == undefined || $rootScope.tspsa ==''){ 555. KunjunganStorage.getLocalstorage("tsp_sa")

556. .then(function(response){ 557. $rootScope.tspsa = response;

558. console.log("sukses mendapatkan nilai TSPSA dari localStorage.");

559. }, 560.

561. function (error) {

562. console.log("error get TSPSA from localstorage: " + error); 563. });

(14)

566.

567. $scope.copytoCliboard = function(text){ 568. $cordovaClipboard

569. .copy(text)

570. .then(function () {

571. console.log("sukses copy cliboard!"); 572. alert("Success copy to clipboard!"); 573. }, function () {

574. console.log("error copy cliboard!"); 575. });

576. }; 577.

578. }) 579.

580. .controller('matrix_dataCtrl', function($scope, $rootScope, KunjunganStorage) {

581. 582.

583. if ($rootScope.tspsa == undefined || $rootScope.tspsa ==''){ 584. KunjunganStorage.getLocalstorage("tsp_sa")

585. .then(function(response){ 586. $rootScope.tspsa = response;

587. console.log("sukses mendapatkan nilai TSPSA dari localStorage.");

588. }, 589.

590. function (error) {

591. console.log("error get TSPSA from localstorage: " + error); 592. });

593. 594. } 595.

596. if ($rootScope.daftarKunjungan == undefined || $rootScope.daftarKunjungan ==''){

597. KunjunganStorage.getLocalstorage("kunjungan") 598. .then(function(response){

599. $rootScope.daftarKunjungan = response; 600.

601. console.log("sukses mendapatkan nilai daftarKunjungan dari localStorage.");

602. }, 603.

604. function (error) {

605. console.log("error get daftarKunjungan from localstorage: " + error);

606. }); 607.

608. } 609. 610. }) 611. 612.

613. .controller('editKoordinatCtrl', function($scope, $http, $rootScope, $ionicLoading) {

614. console.log("edit: " + $rootScope.customerEdit); 615. console.log($rootScope.customers);

616. var customerEdit = $rootScope.customerEdit; 617.

618. alert("Anda ingin edit customer : "+

$rootScope.customers.data.customers[customerEdit].nama); 619.

620. $scope.default_coordinat = function(){

621. var def = $rootScope.customers.data.customers[customerEdit].lat + ', ' + $rootScope.customers.data.customers[customerEdit].lng;

622. alert("Anda yakin set ke koordinat sebelumnya ? \n" + def); 623. $('#coordinat').val(def);

(15)

625.

626. $scope.simpan_coordinat = function(){ 627. var koordinat = $('#coordinat').val(); 628. //validate

629. if (koordinat != null && koordinat!=''){

630. $http.get("http://"+$rootScope.settings.connection +

"/api/customers.php?act=edit_coordinat&kode="+$rootScope.customers.data.c ustomers[customerEdit].kode + "&coordinat="+koordinat)

631. .then(function(response){ 632. console.log(response);

633. alert("Data koordinat berhasil diperbaharui!"); 634. },

635. function(error){ 636. console.log(error);

637. $rootScope.customers = error; 638. });

639. } else

640. alert("Data yang anda isi kosong!"); 641. };

642.

643. $scope.loading = $ionicLoading.show({ 644. content: 'Getting current location...', 645. showBackdrop: false

646. }); 647.

648. $scope.get_gps = function(){ 649.

650. console.log("detectLocation() starting"); 651. if (navigator.geolocation)

652. {

653. console.log("navigator.geolocation is supported"); 654. navigator.geolocation.getCurrentPosition(function (pos){ 655. console.log("geocodePosition() starting");

656. console.log('Got pos', pos);

657. alert(pos.coords.latitude + ", " + pos.coords.longitude); 658. $('#coordinat').val(pos.coords.latitude + ", " +

pos.coords.longitude); 659. },

660. function (error){

661. console.log("error " + error.code);

662. alert('Unable to get location: ' + error.message); 663. }, { timeout: 10000 });

664. } 665. else 666. {

667. console.log("navigator. geolocation not supported"); 668. }

669. 670. }; 671.

672. function watchGeocodePosition(){

673. console.log("watchGeocodePosition() starting"); 674. }

675.

676. $scope.get_pos_from_map = function(){

677. alert("Optional. Direncanakan akan drag and drop marker untuk menuntukan posisi langsung dari maps!");

678. }; 679. 680. });

1.3

js/services/kunjungan.js

1. angular.module('starter')

(16)

3.

4. var markers = []; 5.

6. function getLocationfromServer(user_id, date, setting_connection){ 7.

$http.get("http://"+setting_connection+"/api/kunjungan.php?act=view&techn ical="+user_id+"&tanggal="+date)

8. .then(function(response){ 9. markers = response; 10. return markers; 11. });

12. } 13.

14. function Calculate_TSPSA(user_id, date, setting_connection, parameter){ 15.

$http.get("http://"+setting_connection+"/api/kunjungan.php?act=tsp_sa&tec hnical="+user_id+"&tanggal="+date+parameter)

16. .then(function(response){ 17. data = response; 18. return data; 19. });

20. } 21. 22.

23. function getLocationfromLocalstorage(){ 24.

25. var deferred = $q.defer(); 26. var data = [];

27. var data = JSON.parse(localStorage.getItem('kunjungan')); 28. deferred.resolve(data);

29. return deferred.promise; 30. }

31.

32. function fsaveLocalstorage(data, data_ls){ 33. localStorage.setItem(data_ls , data);

34. console.log("set localStorage " + data_ls + "."); 35. return true;

36. } 37.

38. function fgetLocalstorage(data_ls){ 39. var deferred = $q.defer();

40. var data = [];

41. //var data = localStorage.getItem(data_ls)

42. var data = JSON.parse(localStorage.getItem(data_ls)); 43. deferred.resolve(data);

44. return deferred.promise; 45. }

46.

47. function fcheckNested(obj /*, level1, level2, ... levelN*/) { 48. var args = Array.prototype.slice.call(arguments, 1);

49.

50. for (var i = 0; i < args.length; i++) { 51. if (!obj || !obj.hasOwnProperty(args[i])) { 52. return false;

53. }

54. obj = obj[args[i]]; 55. }

56. return true; 57. }

58.

59. function fsaveKunjungan(data) {

60. var dataKunjungan = localStorage['kunjungan']; 61.

62. localStorage.setItem('kunjungan', JSON.stringify(data)); 63. console.log("set localStorage Kunjungan.");

(17)

66.

67. function cek_date(){ 68. var date = new moment();

69. var current_date = moment(date).format("YYYY-MM-DD"); 70. return current_date;

71. } 72.

73. return { 74.

75. saveKunjungan: function(data){ 76. return fsaveKunjungan(data); 77. },

78. getKunjungan: function(){

79. if(ConnectivityMonitor.isOnline()){

80. setting_connection = $rootScope.settings.connection; 81. user_id = $rootScope.user.reg_id;

82. date = cek_date(); 83.

84. return

$http.get("http://"+setting_connection+"/api/kunjungan.php?act=view&techn ical="+user_id+"&tanggal="+date)

85. .then(function(response){ 86. markers = response; 87. return markers; 88. });

89. }else{

90. alert("tidak terhubung internet"); 91. return getLocationfromLocalstorage(); 92. }

93. },

94. Calculate_TSPSA: function(){

95. setting_connection = $rootScope.settings.connection; 96. user_id = $rootScope.user.reg_id;

97. date = cek_date(); 98. parameter =

'&mTemp='+$rootScope.settings.mTemp+'&mItr='+$rootScope.settings.mItr+'&m Sukses='+$rootScope.settings.mSukses+'&decT='+$rootScope.settings.decT+'& avoid_toll_roads='+$rootScope.settings.avoid_toll_roads+'&optimizewaypoin t='+$rootScope.settings.optimizewaypoint+'&travel_mode='+$rootScope.setti ngs.travel_mode;

99. alert("user_id: "+ user_id + ", date" + date + ", setting_connection" + setting_connection);

100. return

$http.get("http://"+setting_connection+"/api/kunjungan.php?act=tsp_sa&tec hnical="+user_id+"&tanggal="+date+parameter)

101. .then(function(response){ 102. markers = response; 103. return markers; 104. });

105. },

106. saveLocalstorage: function(data, data_ls){ 107. return fsaveLocalstorage(data, data_ls); 108. },

109. getLocalstorage: function(data_ls){ 110. return fgetLocalstorage(data_ls); 111. },

112. cekTanggal: function(){ 113. current_date = cek_date(); 114. return current_date; 115. },

116. cekTanggalJam: function(){ 117. date = new moment();

118. var current_date = moment(date).format("YYYY-MM-DD h:mm:ss a"); 119. return current_date;

120. },

(18)

123. } 124. 125. } 126. })

1.4

js/services/googlemaps.js

1. angular.module('starter')

2. .factory('GoogleMaps', function($rootScope, $state, $cordovaGeolocation, $ionicLoading, $firebase, $ionicPopup, $window,

$cordovaBackgroundGeolocation, $ionicPlatform, $http, KunjunganStorage, ModifyRootScopeService, ConnectivityMonitor, moment){

3.

4. var apiKey = "AIzaSyC3kP8F6zHr8rt4J-_MVTdfwtp28VjbVMg"; 5. $rootScope.map = null;

6. $rootScope.user_track = {}; 7.

8. //ofiice position 9. function variable(){

10. return {"lat": 3.623004, "lng": 98.676711}; 11. }

12.

13. function initMap(){ 14.

15. var options = {timeout: 10000, enableHighAccuracy: true}; 16.

17. 18. 19.

$cordovaGeolocation.getCurrentPosition(options).then(function(position){ 20.

21. console.log(position); 22. $rootScope.latLng = new

google.maps.LatLng(position.coords.latitude, position.coords.longitude); 23.

24. $pos_office = variable();

25. var latLngOffice = new google.maps.LatLng($pos_office.lat, $pos_office.lng);

26.

27. //pengaturan gambar untuk office 28. var imageOffice = {

29. url: 'img/office.png',

30. // This marker is 20 pixels wide by 32 pixels high. 31. size: new google.maps.Size(32, 32),

32. // The origin for this image is (0, 0). 33. origin: new google.maps.Point(0, 0),

34. // The anchor for this image is the base of the flagpole at (0, 32).

35. anchor: new google.maps.Point(16, 32) 36. };

37.

38. var mapOptions = {

39. center: $rootScope.latLng, 40. zoom: 12,

41.

42. mapTypeControlOptions: { 43. mapTypeIds: [

44. google.maps.MapTypeId.ROADMAP, 45. google.maps.MapTypeId.SATELLITE 46. ],

47. position: google.maps.ControlPosition.BOTTOM_LEFT 48. }

49.

(19)

52. $rootScope.map = new

google.maps.Map(document.getElementById("map"), mapOptions); 53. ModifyRootScopeService.setRootScopeValue($rootScope.map); 54.

55. var marker = new google.maps.Marker({ 56. position: latLngOffice,

57. map: $rootScope.map, 58. title: 'BTSSoft Office', 59. icon: imageOffice, 60. /*draggable: true,*/

61. animation: google.maps.Animation.DROP 62. });

63.

64. var imagePeople = { 65. url: 'img/man.png',

66. // This marker is 20 pixels wide by 32 pixels high. 67. size: new google.maps.Size(32, 32),

68. // The origin for this image is (0, 0). 69. origin: new google.maps.Point(0, 0),

70. // The anchor for this image is the base of the flagpole at (0, 32).

71. anchor: new google.maps.Point(16, 32) 72. };

73.

74. $rootScope.markerC = new google.maps.Marker({ 75. position: $rootScope.latLng,

76. map: $rootScope.map, 77. title: 'current Location', 78. draggable: true,

79. icon: imagePeople,

80. animation: google.maps.Animation.DROP 81. });

82.

83. //kirim lokasi setiap inisialisasi map

84. setLocationFirebase($rootScope.ref, $rootScope.user.username, $rootScope.user.pict, position);

85. 86.

87. var infoWindowContent = "<h4>" + 'BTSSoft' + "</h4>"; 88. addInfoWindow(marker, infoWindowContent, 0);

89.

90. loadMarkers(); 91.

92. //load office marker

93. marker.addListener('click', toggleBounce); 94.

95. //Wait until the map is loaded

96. google.maps.event.addListenerOnce($rootscope.map, 'idle', function(){

97.

98. //Load the markers 99. loadMarkers(); 100.

101. }); 102.

103. }, function(error){

104. console.log("Could not get location"); 105.

106. //Load the markers 107. loadMarkers(); 108. });

109. 110. } 111. 112.

(20)

114.

KunjunganStorage.getKunjungan($rootScope.user.reg_id).then(function(marke rs){

115.

116. var records = markers.data.customers; 117. console.log("Markers: ", records); 118. $rootScope.kunjungan = records; 119.

120. //simpan ke localstorage

121. KunjunganStorage.saveKunjungan(records); 122.

123. for (var i = 0; i < records.length; i++) { 124. //alert (records[i].nama);

125.

126. var record = records[i];

127. var markerPos = new google.maps.LatLng(record.lat, record.lng);

128.

129. // Add the markerto the map

130. var marker = new google.maps.Marker({ 131. map: $rootScope.map,

132. animation: google.maps.Animation.DROP, 133. position: markerPos,

134. label: String(i) 135. });

136.

137. var infoWindowContent = "<h4>" + record.nama + "</h4>"; 138.

139. addInfoWindow(marker, infoWindowContent, record); 140.

141. // rootScope.markersKunjungan

142. if ($rootScope.markersKunjungan == undefined) 143. $rootScope.markersKunjungan = [];

144.

145. $rootScope.markersKunjungan.push(marker); 146.

147. } 148.

149. },

150. function (error) {

151. console.log("error get kunjungan from factory"); 152. });

153. 154.

155. } 156.

157. function addInfoWindow(marker, message, record) { 158.

159. var infoWindow = new google.maps.InfoWindow({ 160. content: message

161. }); 162.

163. google.maps.event.addListener(marker, 'click', function () { 164. infoWindow.open($rootScope.map, marker);

165. }); 166.

167. } 168.

169. function enableMap(){ 170. $ionicLoading.hide();

171. $( "map#map" ).removeClass( "disconnected" ); 172. }

173.

174. function disableMap(){ 175. $ionicLoading.show({

(21)

177. template: ' You must be connected to the Internet to view this map. <br/> <ion-spinner></ion-spinner><button class="button button-clear button-light" ng-click="hide()">Hid Loading?</button>',

178. showBackdrop : false, 179. hideOnStateChange : true 180.

181. }); 182.

183. $( "map#map" ).addClass( "disconnected" ); 184.

185. 186. } 187.

188. function loadGoogleMaps(){ 189.

190. $ionicLoading.show({

191. template: 'Loading Google Maps' 192. });

193.

194. //This function will be called once the SDK has been loaded 195. window.mapInit = function(){

196. initMap(); 197. };

198.

199. //Create a script element to insert into the page 200. var script = document.createElement("script"); 201. script.type = "text/javascript";

202. script.id = "googleMaps"; 203. script.async = true; 204. script.defer =true; 205.

206. //Note the callback function in the URL is the one we created above

207. if(apiKey){

208. // script.src = 'http://maps.google.com/maps/api/js?key=' + apiKey + '&callback=mapInit';

209. //script.src = 'http://maps.google.com/maps/api/js?key=' + apiKey + '&sensor=true&callback=initMap';

210. script.src ="https://maps.googleapis.com/maps/api/js?key=" + apiKey + '&callback=mapInit';

211. } 212. else {

213. script.src =

'http://maps.google.com/maps/api/js?sensor=true&callback=mapInit'; 214. }

215.

216. document.body.appendChild(script); 217. enableMap();

218. 219. } 220.

221. function cekTanggal(){

222. //alert("Cek tanggal di factory GoogleMaps!"); 223. date = new moment();

224. var current_date = moment(date).format("YYYY-MM-DD"); 225. dataCUrrentDate =

KunjunganStorage.getLocalstorage("current_date"); 226.

227. console.log("localstorage : " + dataCUrrentDate); 228. console.log("current date " + current_date); 229.

230. if (dataCUrrentDate != current_date){ 231. //alert("tanggal berbeda! perbaharui"); 232.

233. // perbaharui localstorage nnti diisi

(22)

236. KunjunganStorage.saveLocalstorage(current_date_s, 'current_date').then(function(){

237. console.log("sukses diperbaharui"); 238. },

239. function (error) {

240. console.log("error get kunjungan" + error); 241. });

242.

243. $state.go($state.current, {}, {reload: true});//$window.location.reload(true)

244. //window.location.href = "login.html"; 245.

246. } 247. else

248. console.log ("tanggal sama!"); 249. }

250. 251.

252. function checkLoaded(){ 253. // cek tanggal di sini 254. cekTanggal();

255.

256. if(typeof google == "undefined" || typeof google.maps == "undefined"){

257. loadGoogleMaps(); 258. } else {

259. enableMap(); 260. } 261. }

262.

263. function addConnectivityListeners(){ 264.

265. if(ionic.Platform.isWebView()){ 266.

267. // Check if the map is already loaded when the user comes online,

268. //if not, load it

269. $rootScope.$on('$cordovaNetwork:online', function(event, networkState){

270.

271. checkLoaded(); 272. });

273.

274. // Disable the map when the user goes offline

275. $rootScope.$on('$cordovaNetwork:offline', function(event, networkState){

276. disableMap(); 277. });

278.

279. } 280. else { 281.

282. //Same as above but for when we are not running on a device 283. window.addEventListener("online", function(e) {

284. checkLoaded(); 285.

286. // cek tanggal 287. //if(date) 288. }, false); 289.

290. window.addEventListener("offline", function(e) { 291. disableMap();

292. }, false); 293. }

(23)

297. $rootScope.showAlert = function() { 298. $ionicPopup.alert({

299. title: 'iMapApp',

300. template: 'Your location has been saved!!' 301. });

302. }; 303.

304.

305. function clearMarkers(){ 306. alert("cek markser kosong");

307. console.log("masuk ke function cek marker!"); 308. }

309.

310. function setLocationFirebase(ref, username, gambar, pos){ 311. if(gambar=="undefined")

312. gambar='';

313. //set data into firebase

314. var refTechnical = ref.child("technical"); 315. var userLocation = refTechnical.child(username); 316. userLocation.set({

317. location : {lat: pos.coords.latitude, lng: pos.coords.longitude},

318. last_connect : KunjunganStorage.cekTanggalJam(), 319. status: "connected",

320. address:"Jl. Bilal No 56 A Medan", 321. text:"sudah terkirim dari client", 322. name: username,

323. image: gambar 324.

325. }); 326. } 327.

328. function setCenter(lat, lng){

329. var myLatLng = new google.maps.LatLng(lat, lng); 330. rootScope.map.setCenter(myLatLng);

331. } 332. 333. 334.

335. function clearMapMarkers() {

336. if($rootScope.markersKunjungan !== undefined && $rootScope.markersKunjungan.length > 0){

337. for (var i=0; i<$rootScope.markersKunjungan.length; i++) { 338. $rootScope.markersKunjungan[i].setMap(null);

339. } 340. } 341. 342. } 343.

344. // Removes map directions 345. function clearDirections() {

346. // If there are directions being shown, clear them 347. if ($rootScope.directionsDisplay != null) {

348. $rootScope.directionsDisplay.setMap(null); 349. $rootScope.directionsDisplay = null; 350. }

351. } 352.

353. function cekVariable(){

354. if ($rootScope.tspsa == undefined || $rootScope.tspsa ==''){ 355. KunjunganStorage.getLocalstorage("tsp_sa")

356. .then(function(response){ 357. $rootScope.tspsa = response;

358. console.log("sukses mendapatkan nilai TSPSA dari localStorage.");

(24)

361. function (error) {

362. console.log("error get TSPSA from localstorage: " + error); 363. });

364.

365. } 366.

367. if ($rootScope.daftarKunjungan == undefined || $rootScope.daftarKunjungan ==''){

368. KunjunganStorage.getLocalstorage("kunjungan") 369. .then(function(response){

370. $rootScope.daftarKunjungan = response;

371. //console.log($rootScope.daftarKunjungan[0].nama); 372.

373. console.log("sukses mendapatkan nilai daftarKunjungan dari localStorage.");

374. }, 375.

376. function (error) {

377. console.log("error get daftarKunjungan from localstorage: " + error);

378. }); 379.

380. } 381. } 382.

383. function AddRoute(route){ 384. clearDirections(); 385. cekVariable(); 386.

387. $rootScope.directionsService = new google.maps.DirectionsService();

388. $rootScope.directionsDisplay = new google.maps.DirectionsRenderer();

389. $rootScope.directionsDisplay.setMap($rootScope.map); 390. $rootScope.waypts = [];

391. for (var i = 1; i < route.length; i++) { 392. $rootScope.waypts.push({

393. location: $rootScope.daftarKunjungan[route[i]].lat + " ," + $rootScope.daftarKunjungan[route[i]].lng,

394. stopover: true 395. });

396. } 397.

398. // Add final route to map 399. var request = {

400. origin: $rootScope.daftarKunjungan[route[0]].lat + " ," + $rootScope.daftarKunjungan[route[0]].lng,

401. destination: $rootScope.daftarKunjungan[route[0]].lat + " ," + $rootScope.daftarKunjungan[route[0]].lng,

402. waypoints: $rootScope.waypts,

403. travelMode: $rootScope.settings.travel_mode, 404. avoidHighways: $rootScope.settings.avoid_highaway, 405. avoidTolls: $rootScope.settings.avoid_toll_roads 406. };

407. $rootScope.directionsService.route(request, function(response, status) {

408. if (status == google.maps.DirectionsStatus.OK) {

409. $rootScope.directionsDisplay.setDirections(response); 410. }

411. clearMapMarkers(); 412. });

413. } 414. 415. 416.

417. return {

(25)

419. // initMap(); 420. // },

421. init: function(key){ 422.

423. if(typeof key != "undefined"){ 424. apiKey = key;

425. } 426.

427. if(typeof google == "undefined" || typeof google.maps == "undefined"){

428.

429. console.warn("Google Maps SDK needs to be loaded"); 430.

431. disableMap(); 432.

433. if(ConnectivityMonitor.isOnline()){ 434. loadGoogleMaps();

435. } 436. } 437. else {

438. if(ConnectivityMonitor.isOnline()){ 439. initMap();

440. enableMap(); 441.

442. var networkState = navigator.connection.type; 443. console.log('Connection type: ' + networkState); 444.

445. } else {

446. disableMap(); 447. }

448. }

449. //for checking connectivity 450. addConnectivityListeners(); 451.

452. }, 453.

454. centerMe: function(ref, username, gambar){ 455.

456. if (!$rootScope.map) { 457. return;

458. } 459.

460. if (navigator.geolocation) 461. {

462. $rootScope.markerC.setMap(null);

463. console.log("navigator.geolocation is supported"); 464. navigator.geolocation.getCurrentPosition(function (pos){ 465. console.log("geocodePosition() starting");

466. console.log('Got pos', pos);

467. var myLatLng = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);

468. $rootScope.map.setCenter(myLatLng); 469.

470. var imagePeople = { 471. url: 'img/man.png',

472. // This marker is 20 pixels wide by 32 pixels high. 473. size: new google.maps.Size(32, 32),

474. // The origin for this image is (0, 0). 475. origin: new google.maps.Point(0, 0),

476. // The anchor for this image is the base of the flagpole at (0, 32).

477. anchor: new google.maps.Point(16, 32) 478. };

479.

480. $rootScope.markerC = new google.maps.Marker({ 481. position: myLatLng,

(26)

483. title: 'current Location', 484. icon: imagePeople,

485. draggable: true

486. //animation: google.maps.Animation.DROP 487. });

488.

489. setLocationFirebase(ref, username, gambar, pos); 490. //"https://glowing-torch-4411.firebaseio.com/test/" 491. // var location = [pos.coords.latitude,

pos.coords.longitude];

492. // var refLocation = ref.child("Location");

493. // var UserrefLocation = refLocation.child(username); 494. // UserrefLocation.set({

495. // g:"test", 496. // l:location 497.

498. // }); 499.

500. 501.

502. },

503. function (error){

504. console.log("error " + error.code);

505. alert('Unable to get location: ' + error.message); 506. $scope.loading.hide();

507. }, { timeout: 10000 }); 508.

509. } 510. else 511. {

512. console.log("navigator.geolocation not supported"); 513. }

514.

515. $rootScope.user_track = {};

516. google.maps.event.addListener($rootScope.markerC, 'dragend', function(evt){

517. console.log('Current Latitude:',evt.latLng.lat(),'Current Longitude:',evt.latLng.lng());

518. scope.$parent.user_track.latitude = evt.latLng.lat(); 519. scope.$parent.user_track.longitude = evt.latLng.lng(); 520. scope.$apply();

521. }); 522.

523. },

524. reloadMarkers: function(){ 525. loadMarkers();

526. },

527. sendLocation: function(){ 528. firebasesend();

529. },

530. clearMarkersMap: function(){ 531. clearMarkers();

532. },

533. cekTanggal: function(){ 534. cekTanggal();

535. },

536. hitungButton: function(){

537. console.log($rootscope.kunjungan); 538. alert($rootscope.kunjungan); 539. },

540. setCenterOffice: function(){ 541. pos = variable();

542. setCenter(pos.lat, pos.lng); 543. rootScope.map.setCenter(myLatLng); 544. },

(27)

547. },

548. clearDirections:function(){ 549. clearDirections();

(28)

2.

API Server PHP

2.1

Api/api.php

1.

<?php

2.

header ('Access-Control-Allow-Origin: *');/// memungkinkan untuk permintaan pemanggilan cross domain

3.

header("Content-Type: application/json; charset=UTF-8");

4.

header('Access-Control-Allow-Methods: GET, POST');

5.

require_once "../config/dbconfig.php";

6.

7.

if(isset($_GET['type'])){

8.

if ($_GET['type'] == 'login'){

9.

$email = $_GET['email'];

10.

$password = md5($_GET['password']);

11.

12.

$query = "SELECT `reg_id`, `reg_date`, `username`, `fullname`, `email`, `pict` from `user` where `email`='$email' and `password`='$password' and `client`=1 and `status`=1";

13.

14.

$result1 = mysqli_query($dbc, $query);

15.

$totalRows = mysqli_num_rows($result1);

16.

17.

if($totalRows > 0){

18.

$recipes = array();

19.

$recipes['success'] = true;

20.

$recipes['code'] = 200;

21.

22.

while($recipe = mysqli_fetch_assoc($result1)){

23.

$recipes[] = $recipe ;

24.

}

25.

26.

$output = json_encode($recipes);

27.

28.

echo $output;

29.

30.

}else{

31.

$recipes = array();

32.

$recipes['success'] = false;

33.

$recipes['code'] = 400;

34.

$recipes['messages'] = 'Username atau password salah';

35.

$recipes['mysql_error'] = mysqli_error($dbc);

36.

$recipes['email'] = $email;

37.

$recipes['password'] = $password;

38.

echo $output = json_encode($recipes);

39.

40.

}

41.

42.

}//type login

43.

else echo "tidak ada type login";

44.

}//isset type

45.

else echo "type cannot found";

46.

?>

2.2

Api/customers.php

(29)

2.

//Set these headers to avoid any issues with cross origin resource sharing issues

3.

header('Access-Control-Allow-Origin: *');

4.

header('Access-Control-Allow-Methods: GET, POST, OPTIONS');

5.

header('Access-Control-Allow-Headers:

Content-Type,x-prototype-version,x-requested-with');

6.

7.

//Output the result to the browser so that our Ionic application can see the data

8.

9.

//Create a connection to the database

10.

require_once "../config/dbconfig.php";

11.

12.

//The default result to be output to the browser

13.

$result = "{'success':false}";

14.

15.

16.

#view

17.

if ($_GET['act'] == 'view'){

18.

//Select everything from the table containing the marker informaton

19.

$query = "SELECT * FROM `customers`";

20.

21.

//Run the query

22.

$dbresult = $dbc->query($query);

23.

24.

//Build an array of markers from the result set

25.

$markers = array();

26.

27.

while($row = $dbresult->fetch_array(MYSQLI_ASSOC)){

28.

29.

$markers[] = array(

30.

'kode' => $row['Kode'],

31.

'nama' => $row['Nama'],

32.

'alamat' => $row['Alamat'],

33.

'telp_fax' => $row['TelpFax'],

34.

'email' => $row['mEmail'],

35.

'pict' => $row['pict'],

36.

'lat' => $row['Latitude'],

37.

'lng' => $row['Longitude']

38.

);

39.

}

40.

41.

//If the query was executed successfully, create a JSON string containing the marker information

42.

if($dbresult){

43.

$result = '{"success":true, "customers":' . json_encode($markers) . '}';

44.

}

45.

else

46.

{

47.

$result = "{'success':false, 'mysql_error':"+mysqli_error($dbc)+"}";

48.

}

49.

50.

echo($result);

51.

}

(30)

53.

54.

#edit_coordinat

55.

if ($_GET['act'] == 'edit_coordinat'){

56.

$kode=mysqli_real_escape_string($dbc, htmlspecialchars(trim($_GET['kode'])));

57.

$coordinat=mysqli_real_escape_string($dbc, htmlspecialchars(trim($_GET['coordinat'])));

58.

59.

$coor = explode(",", $coordinat);

60.

$lat = $coor[0];

61.

$lng = $coor[1];

62.

63.

$query = "UPDATE `customers` SET `Latitude` = $lat, `Longitude` = $lng WHERE `Kode`='$kode'";

64.

65.

//Run the query

66.

if (mysqli_query($dbc, $query)){

67.

68.

$result = '{"success":true, "messages":"success update data '.$_GET['kode'].'"}';

69.

70.

} else {

71.

$result = "{'success':false, 'mysql_error':"+mysqli_error($dbc)+"}";

72.

}

73.

74.

}

75.

76.

?>

2.3

Api/kunjungan.php

1. <?php

2. //Set these headers to avoid any issues with cross origin resource sharing issues

3. header('Access-Control-Allow-Origin: *');

4. header('Access-Control-Allow-Methods: GET, POST, OPTIONS'); 5. header('Access-Control-Allow-Headers:

Content-Type,x-prototype-version,x-requested-with'); 6.

7. //Create a connection to the database 8. require_once "../config/dbconfig.php"; 9.

10. //The default result to be output to the browser 11. $result = "{'success':false}";

12. $modified_date = date('Y-m-d H:i:s'); 13. $start_timer = microtime(true);

14.

15. if ($_GET['act']=='add'){ 16.

17. $query = "INSERT INTO kunjungan (pelanggan, technical, tanggal) VALUES

('".$_GET['pelanggan']."',".htmlspecialchars(trim($_GET['technical'])).", NOW())";

18.

19. //Run the query

20. if ($dbc->query($query)){

21. $q_kunjungan = "SELECT b.`Kode`, b.`Nama`, b.`Alamat`, b.`TelpFax`, b.`mEmail`, b.`pict`, b.`Latitude`, b.`Longitude` FROM `customers` b WHERE b.`kode` = '" . $_GET['pelanggan'] . "'"; 22. $dbresult = $dbc->query($q_kunjungan);

(31)

24. $kunjungan = array();

25.

26. while($row = $dbresult->fetch_array(MYSQLI_ASSOC)){

27.

28. $kunjungan["$row[Kode]"] = array( 29. 'kode' => $row['Kode'],

30. 'nama' => $row['Nama'], 31. 'alamat' => $row['Alamat'], 32. 'telp_fax' => $row['TelpFax'], 33. 'email' => $row['mEmail'], 34. 'pict' => $row['pict'], 35. 'lat' => $row['Latitude'], 36. 'lng' => $row['Longitude'], 37. 'permasalahan' => '', 38. 'tanggal_selesai' => '', 39. 'status' => 0,

40. 'keterangan' => ''

41. );

42. }

43.

44. //If the query was executed successfully, create a JSON string containing the marker information

45. if($dbresult){

46. $result = '{"success":true, "customers":' . json_encode($kunjungan) . '}';

47. }

48. else

49. {

50. $result = "{'success':false, 'mysql_error':"+mysqli_error($dbc)+"}";

51. }

52. } else {

53. $result = "{'success':false, 'mysql_error':"+mysqli_error($dbc)+"}"; 54. }

55. 56. 57. 58. } 59.

60. if ($_GET['act']== 'view'){

61. $query = "SELECT a.`pelanggan`, a.`technical`, a.`permasalahan`, a.`tanggal`, a.`tanggal_selesai`, a.`status`, a.`keterangan`, b.`Kode`, b.`Nama`, b.`Alamat`, b.`TelpFax`, b.`mEmail`, b.`pict`, b.`Latitude`, b.`Longitude` FROM `kunjungan` a LEFT JOIN `customers` b ON a.`pelanggan` = b.`kode` WHERE

a.`technical`=".htmlspecialchars(trim($_GET['technical']))." AND a.`tanggal`='".htmlspecialchars(trim($_GET['tanggal']))."' ORDER BY a.`sa_path`";

62.

63. //Run the query

64. $dbresult = $dbc->query($query);

65. //Build an array of markers from the result set 66. $kunjungan = array();

67.

68. while($row = $dbresult->fetch_array(MYSQLI_ASSOC)){ 69.

70. $kunjungan[] = array( 71. 'kode' => $row['Kode'], 72. 'nama' => $row['Nama'], 73. 'alamat' => $row['Alamat'], 74. 'telp_fax' => $row['TelpFax'], 75. 'email' => $row['mEmail'], 76. 'pict' => $row['pict'], 77. 'lat' => $row['Latitude'], 78. 'lng' => $row['Longitude'],

(32)

80. 'tanggal_selesai' => $row['tanggal_selesai'], 81. 'status' => $row['status'],

82. 'keterangan' => $row['keterangan']

83. );

84. } 85.

86. //If the query was executed successfully, create a JSON string containing the marker information

87. if($dbresult){

88. $result = '{"success":true, "customers":' . json_encode($kunjungan) . '}';

89. } 90. else 91. {

92. $result = "{'success':false, 'mysql_error':"+mysqli_error($dbc)+"}"; 93. }

94. } 95.

96. if ($_GET['act'] == 'delete') {

97. $pelanggan=mysqli_real_escape_string($dbc, htmlspecialchars(trim($_GET['pelanggan']))); 98. $technical=mysqli_real_escape_string($dbc,

htmlspecialchars(trim($_GET['technical']))); 99. $tanggal=mysqli_real_escape_string($dbc,

htmlspecialchars(trim($_GET['tanggal'])));

100. $query = "DELETE FROM `btssoft_tspsa`.`kunjungan` WHERE `kunjungan`.`pelanggan` = '$pelanggan' AND `kunjungan`.`technical` = '$technical' AND `kunjungan`.`tanggal` = '$tanggal';";

101.

102. //Run the query

103. if (mysqli_query($dbc, $query)){

104.

105. $result = '{"success":true, "messages":"success delete '.$_GET['pelanggan'].'"}';

106.

107. } else {

108. $result = "{'success':false, 'mysql_error':"+mysqli_error($dbc)+"}";

109. }

110. 111.

112.

113. } 114.

115. if ($_GET['act']== 'tsp_sa'){ 116.

117. //Select everything from the table containing 'kunjungan' informaton

118. $query = "SELECT a.`pelanggan`, a.`technical`, a.`permasalahan`, a.`tanggal`, a.`tanggal_selesai`, a.`status`,

a.`keterangan`, b.`Kode`, b.`Nama`, b.`Alamat`, b.`TelpFax`, b.`mEmail`, b.`pict`, b.`Latitude`, b.`Longitude` FROM `kunjungan` a LEFT JOIN `customers` b ON a.`pelanggan` = b.`kode` WHERE

a.`technical`=".htmlspecialchars(trim($_GET['technical']))." AND a.`tanggal`='".htmlspecialchars(trim($_GET['tanggal']))."' ORDER BY a.`sa_path`";

119.

120. //Run the query

121. $dbresult = $dbc->query($query); 122.

123. //membagun data daftar kunjungan 124. $l_tsp = array();

125. $i=1;

126. $qb_def = ''; 127.

(33)

129. $qb_def .= "UPDATE `kunjungan` SET `def_path`=". $i++ . ", `calc_date`='".$modified_date."' WHERE

`technical`='".htmlspecialchars(trim($_GET['technical']))."' AND `tanggal`='".$_GET['tanggal'] . "' AND `pelanggan`='" .

$row['pelanggan']."' ; 130. ";

131. $kunjungan[] = array( 132. 'kode' => $row['Kode'], 133. 'nama' => $row['Nama'], 134. 'alamat' => $row['Alamat'], 135. // 'telp_fax' => $row['TelpFax'], 136. // 'email' => $row['mEmail'], 137. // 'pict' => $row['pict'], 138. 'lat' => $row['Latitude'], 139. 'lng' => $row['Longitude'],

140. // 'permasalahan' => $row['permasalahan'], 141. // 'tanggal_selesai' => $row['tanggal_selesai'], 142. // 'status' => $row['status'],

143. // 'keterangan' => $row['keterangan']

144. );

145. }

146.

147.

148. //If the query was executed successfully 149. if($dbresult){

150. $messages_update_sa = ''; 151.

152. if (count($dbresult)==0)

153. $result = '{"success":true,

"status":"DATA_KOSONG", "messages":"Data kunjungan kosong"}';

154. else {

155. $key = "AIzaSyC3kP8F6zHr8rt4J-_MVTdfwtp28VjbVMg"; //key browser

156. //$key =

"AIzaSyBbtjGe0v3DR3dFEuYuVl2Qq_vVyzbg7PM"; //optional key server

157. //$key =

"AIzaSyDnDtXKxwBi5ebslG3Z4hiN54JpGkgjIfs"; //optional key broser 2 158. include "function_tsp.php";

159.

160. //update lokasi default

161. if (mysqli_multi_query($dbc, $qb_def)) 162. $messages_update_def = "Sukses update

default path";

163. else

164. $messages_update_def = mysqli_error($dbc); 165.

166. $parameter ='';

167. //cek parameter google

168. if (!isset($_GET['travel_mode'])) 169. $_GET['travel_mode']="driving"; 170. if(isset($_GET['avoid_toll_roads']) and

$_GET['avoid_toll_roads']==true)

171. $parameter .= '&avoid=tools';

172. if(!isset($_GET['optimizewaypoint']) || $_GET['optimizewaypoint']==true)

173. $parameter .= "&waypoints=optimize:true"; 174. if(!isset($_GET['travel_mode']) and

$_GET['travel_mode']== "WALKING")

175. $parameter .= "mode=walking"; 176.

177. //ambil matrix data jarak dan waktu tempuh dari google maps

178. $result_a = GetDrivingDistance($kunjungan, $key, $parameter);

179. if ($result_a['status'] == 'OK'){

180. $matrix = $result_a['rows'];

Referensi

Dokumen terkait

Dari hasil temuan dan analisis penelitian, ada beberapa hal yang dapat dijadikan sebagai saran atau masukan, antara lain bagi (1) Kepala sekolah hendaknya

Al-Ghazali menasehati kepada para pendidik Islam agar memiliki sifat-sifat sebagai berikut: a) Seorang guru harus menaruh rasa kasih sayang terhadap murid- muridnya

Kualitas mikroskopik spermatozoa dibedakan menjadi motilitas, morfologi, integritas membran, jumlah spermatozoa dan leukosit dalam saluran reproduksi, dan aglutinasi spermatozoa

“The Balanced Scorecard translates an organization’s mission and strategy into operational and performance measures for four different perspective: the financial perspective,

Model Creative Problem Solving (CPS) adalah suatu model pembelajaran yang berpusat pada kemampuan pemecahan masalah, yang diikuti dengan penguatan kreatifitas dan

Sedangkan untuk latihan berbeban atau weight training merupakan salah satu bentuk latihan fisik yang dalam pelaksanaannya dapat menggunakan bantuan tubuhnya sendiri bahkan

Dengan mempelajari bagian ini sebelum praktikum, praktikan mempersiapkan dirinya untuk suatu pengalaman praktis menguji coba konsep yang dijelaskan dalam tujuan dan

Besarnya f hitung &gt; f tabel dengan signifikasi (0,000&lt;0,005) dapat disimpulkan bahwa terdapat pengaruh bersama-sama dan signifikan pengalaman, otonomi,