app.js 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261
  1. // file:///Users/francoisbeaufils/Downloads/geocoder-demo-master/index.html
  2. var app = angular.module('application', ['ngMaterial', 'adaptive.detection', 'ui.bootstrap.typeahead']);
  3. app.directive('skrollr', function() {
  4. var directiveDefinitionObject = {
  5. link: function() {
  6. skrollr.init();
  7. }
  8. };
  9. return directiveDefinitionObject;
  10. });
  11. app.controller('mainController', function($scope, $detection, $http, $mdSidenav, $timeout, $sce, $mdToast) {
  12. $scope.title = "Manche Numerique";
  13. var getGeoCodeInProgress = false,
  14. nbJoursFTTH = 244,
  15. siteName = 'Eligibilité Manche Numérique',
  16. siteUrl = 'http://eligibilite.manchenumerique.fr',
  17. siteEmail = 'ftth@manchenumerique.fr',
  18. siteAddresse = '235, rue Joseph Cugnot Zone Delta, 50000 SAINT LÔ',
  19. layer = {},
  20. currentMarker, searchExtent;
  21. var catTypeVoie = [
  22. {
  23. "name": "Allée",
  24. "id" : "allee"
  25. },
  26. {
  27. "name": "Avenue",
  28. "id" : "avenue"
  29. },
  30. {
  31. "name": "Boulevard",
  32. "id" : "boulevard"
  33. },
  34. {
  35. "name": "Carrefour",
  36. "id" : "carrefour"
  37. },
  38. {
  39. "name": "Chemin",
  40. "id" : "chemin"
  41. },
  42. {
  43. "name": "Cité",
  44. "id" : "cite"
  45. },
  46. {
  47. "name": "Hammeau",
  48. "id" : "hammeau"
  49. },
  50. {
  51. "name": "Impasse",
  52. "id" : "impasse"
  53. },
  54. {
  55. "name": "Lieu-dit",
  56. "id" : "lieu_dit"
  57. },
  58. {
  59. "name": "Lotissement",
  60. "id" : "lotissement"
  61. },
  62. {
  63. "name": "Place",
  64. "id" : "place"
  65. },
  66. {
  67. "name": "Résidence",
  68. "id" : "residence"
  69. },
  70. {
  71. "name": "Route",
  72. "id" : "route"
  73. },
  74. {
  75. "name": "Rue",
  76. "id" : "rue"
  77. },
  78. {
  79. "name": "Villa",
  80. "id" : "villa"
  81. },
  82. {
  83. "name": "Village",
  84. "id" : "village"
  85. }
  86. ];
  87. var catVousEtes = [
  88. {
  89. "name": "Locataire de ce logement",
  90. "id" : "locataire"
  91. },
  92. {
  93. "name": "Occupant à titre gratuit de ce logement",
  94. "id" : "occupant_gratuit"
  95. },
  96. {
  97. "name": "Propriétaire de ce logement",
  98. "id" : "proprietaire"
  99. }
  100. ];
  101. var catCeLogementEst = [
  102. {
  103. "name": "Votre résidence principale",
  104. "id" : "residence_principale"
  105. },
  106. {
  107. "name": "Votre résidence secondaire",
  108. "id" : "residence_secondaire"
  109. }
  110. ];
  111. $scope.formulaires = {
  112. "eligibilite": {
  113. "sections": [
  114. {
  115. "name": "Générale",
  116. "visible": false,
  117. "lines": [
  118. {
  119. "ctrls": [
  120. {
  121. "name" : "Prénom",
  122. "id" : "prenom",
  123. "type" : "text",
  124. "width" : "50%",
  125. "require": true,
  126. "isValid": function(value) {
  127. return !!value && value.length > 2;
  128. },
  129. "msg" : 'Prénom invalide'
  130. },
  131. {
  132. "name" : "Nom",
  133. "id" : "nom",
  134. "type" : "text",
  135. "width" : "50%",
  136. "require": true,
  137. "isValid": function(value) {
  138. return !!value && value.length > 2;
  139. },
  140. "msg" : 'Nom invalide'
  141. }
  142. ]
  143. },
  144. {
  145. "ctrls": [
  146. {
  147. "name" : "Email",
  148. "id" : "email",
  149. "type" : "text",
  150. "width" : null,
  151. "require": true,
  152. "isValid": function(value) {
  153. function validateEmail(email) {
  154. var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
  155. return re.test(email);
  156. }
  157. return validateEmail(value);
  158. },
  159. "msg" : 'Email invalide.'
  160. }
  161. ]
  162. },
  163. {
  164. "ctrls": [
  165. {
  166. "name" : "Téléphone fixe",
  167. "id" : "telephone_fixe",
  168. "type" : "text",
  169. "width" : "50%",
  170. "require": false
  171. },
  172. {
  173. "name" : "Téléphone portable",
  174. "id" : "telephone_portable",
  175. "type" : "text",
  176. "width" : "50%",
  177. "require": false
  178. }
  179. ]
  180. }
  181. ]
  182. },
  183. {
  184. "name": "Adresse",
  185. "visible": true,
  186. "lines": [
  187. {
  188. "ctrls": [
  189. {
  190. "name" : "Numero",
  191. "id" : "numero_voie",
  192. "type" : "text",
  193. "width" : "80px",
  194. "require": false
  195. },
  196. {
  197. "name" : "Type voie",
  198. "id" : "type_voie",
  199. "type" : "select",
  200. "width" : "106px",
  201. "require": false,
  202. "options": {
  203. "categories": catTypeVoie
  204. }
  205. },
  206. {
  207. "name" : "Nom voie",
  208. "id" : "nom_voie",
  209. "type" : "text",
  210. "width" : "378px",
  211. "require": true,
  212. "isValid": function(value) {
  213. return !!value;
  214. },
  215. "msg" : 'Nom de voie invalide.'
  216. }
  217. ]
  218. },
  219. {
  220. "ctrls": [
  221. {
  222. "name" : "Complément Adresse",
  223. "id" : "complement_addresse",
  224. "type" : "textarea",
  225. "width" : null,
  226. "require": false
  227. }
  228. ]
  229. },
  230. {
  231. "ctrls": [
  232. {
  233. "name" : "Bâtiment",
  234. "id" : "batiment",
  235. "type" : "text",
  236. "width" : "50%",
  237. "require": false
  238. },
  239. {
  240. "name" : "Cage escalier",
  241. "id" : "cage_escalier",
  242. "type" : "text",
  243. "width" : "50%",
  244. "require": false
  245. }
  246. ]
  247. },
  248. {
  249. "ctrls": [
  250. {
  251. "name" : "Etage / Niveau",
  252. "id" : "etage",
  253. "type" : "text",
  254. "width" : "50%",
  255. "require": false
  256. },
  257. {
  258. "name" : "Numero appartement / porte",
  259. "id" : "numero_appartement",
  260. "type" : "text",
  261. "width" : "50%",
  262. "require": false
  263. }
  264. ]
  265. },
  266. {
  267. "ctrls": [
  268. {
  269. "name" : "Code postal",
  270. "id" : "code_postal",
  271. "type" : "text",
  272. "width" : "50%",
  273. "require": true,
  274. "isValid": function(value) {
  275. if(!value || value.length !== 5 || isNaN(parseInt(value, 10))) {
  276. return false;
  277. }
  278. return true;
  279. },
  280. "msg" : 'Non valide'
  281. },
  282. {
  283. "name" : "Ville",
  284. "id" : "ville",
  285. "type" : "text",
  286. "width" : "50%",
  287. "require": true,
  288. "isValid": function(value) {
  289. return !!value && value.length > 2;
  290. },
  291. "msg" : 'Ville invalide.'
  292. }
  293. ]
  294. }
  295. ]
  296. },
  297. {
  298. "name": "Logement",
  299. "visible": true,
  300. "lines": [
  301. {
  302. "ctrls": [
  303. {
  304. "name" : "Vous êtes",
  305. "id" : "vous_etes",
  306. "type" : "radio",
  307. "width" : null,
  308. "require": true,
  309. "options": {
  310. "categories": catVousEtes,
  311. "alertes": {
  312. "locataire": "Si vous êtes locataire, vous devez impérativement avertir votre propriétaire que vous souhaitez bénéficier du pré-raccordement à la fibre optique."
  313. }
  314. },
  315. "isValid": function(value) {
  316. return !!value;
  317. },
  318. "msg" : 'Vous devez sélectionner une entrée.'
  319. }
  320. ]
  321. },
  322. {
  323. "ctrls": [
  324. {
  325. "name" : "Ce logement est",
  326. "id" : "ce_logement_est",
  327. "type" : "radio",
  328. "width" : null,
  329. "require": true,
  330. "options": {
  331. "categories": catCeLogementEst
  332. },
  333. "isValid": function(value) {
  334. return !!value;
  335. },
  336. "msg" : 'Vous devez sélectionner une entrée.'
  337. }
  338. ]
  339. }
  340. ]
  341. },
  342. {
  343. "name": "Conditions pour le raccordement final d’abonné dans un immeuble individuel",
  344. "visible": true,
  345. "lines": [
  346. {
  347. "text": "Le Syndicat Mixte Manche Numérique, composé du Département de la Manche et des Etablissements Publics de Coopération Intercommunale (EPCI) du département, a pour mission l'aménagement numérique du territoire manchois, du point de vue tant des réseaux que du développement des usages du numérique.\r\nDans ce cadre, Manche Numérique a élaboré un Schéma Directeur Territorial d'Aménagement Numérique (SDTAN), qui vise une couverture FTTH (fibre optique jusqu’à l’abonné) universelle du département. Le SDTAN prévoit ainsi le déploiement d’un réseau de communications électroniques à très haut débit FTTH sur le territoire de la Manche.\r\nManche Numérique assurera le déploiement de ce réseau public sous sa maîtrise d’ouvrage. S’agissant de l’exploitation du réseau, celle-ci sera confiée à un délégataire de service public désigné par Manche Numérique à l’issue d’une procédure de mise en concurrence. Le futur gestionnaire du réseau aura en charge notamment sa commercialisation auprès des opérateurs de communications électroniques (les fournisseurs d’accès à internet), qui eux-mêmes délivreront des services de communications électroniques aux utilisateurs finals (les abonnés).\r\nDans le cadre du déploiement de ce réseau, Manche Numérique réalise sous sa maîtrise d’ouvrage des raccordements finals d’abonnés au futur réseau, qui seront ensuite remis au futur délégataire de service public en vue de leur gestion.\r\nC’est dans ce contexte que Manche Numérique propose aux intéressés qui le souhaitent, de faire d’ores et déjà raccorder leur logement ou local à usage professionnel, au futur réseau de communications électroniques à très haut débit FTTH.",
  348. "ctrls": [
  349. {
  350. "name" : "Accord",
  351. "id" : "accord",
  352. "libelle": "Je souhaite être pré-raccordé au réseau de fibre optique et accepte les conditions de paiement de 50€. IMPORTANT : le règlement ne vous sera demandé qu’après travaux effectués",
  353. "type" : "checkbox",
  354. "width" : null,
  355. "require": true,
  356. "isValid": function(value) {
  357. return !!value;
  358. },
  359. "msg" : 'Vous devez doner votre accord.'
  360. }
  361. ]
  362. }
  363. ]
  364. },
  365. {
  366. "name": "Informatique et libertés",
  367. "visible": false,
  368. "lines": [
  369. {
  370. "ctrls": [
  371. {
  372. "name" : "Informatique et libertés",
  373. "id" : "info_et_libertes",
  374. "libelle": 'La personne responsable du traitement de la présente demande de pré-raccordement est le représentant du Syndicat Mixte Manche Numérique, le Président, Monsieur Serge DESLANDES. Les informations portées sur ce formulaire sont obligatoires. Elles font l’objet d’un traitement informatisé destiné au raccordement final de l’usager à la fibre optique (FTTH) ainsi qu’à l’exploitation du réseau optique. Les destinataires des données sont : le Syndicat Mixte Manche Numérique, les entreprises en charge de réaliser les travaux de raccordement, ainsi que l’exploitant du réseau optique. Conformément à la loi "informatique et libertés" du 6 janvier 1978 modifiée, vous bénéficiez d’un droit d’accès, de rectification aux informations qui vous concernent, d’opposition au traitement de vos données personnelles. Si vous souhaitez exercer ce droit et obtenir communication des informations vous concernant, veuillez-vous adresser au Syndicat Mixte Manche Numérique ftth@manchenumerique.fr. Dans l’hypothèse où le présent formulaire est incomplet et/ou illisible, la présente demande de raccordement ne sera pas traitée.',
  375. "type" : "checkbox",
  376. "width" : null,
  377. "require": true,
  378. "isValid": function(value) {
  379. return !!value;
  380. },
  381. "msg" : 'Vous devez accepter.'
  382. }
  383. ]
  384. }
  385. ]
  386. }
  387. ]
  388. }
  389. };
  390. var addCurrentMarker = function() {
  391. if(currentMarker) {
  392. map.removeLayer(currentMarker);
  393. }
  394. currentMarker = L.marker([$scope.geoCode.y, $scope.geoCode.x], {draggable: true, title: "texst"}).addTo(map); //.bindPopup(data.locations[0].name).openPopup();
  395. currentMarker.bindPopup("L'adresse que vous nous avez fournie est localisée sur la carte. Il se peut que la position réelle de votre logement soit un peu différente. Dans ce cas, merci de déplacer le pointeur sur la carte pour le positionner à l'emplacement de votre logement.").openPopup();
  396. reverseLocation($scope.geoCode, null, function(address) {
  397. $scope.address = address;
  398. });
  399. currentMarker.on('dragend', function(event) {
  400. var p = currentMarker.getLatLng();
  401. //console.log('dragend', p);
  402. $scope.geoCode = {
  403. x: p.lng,
  404. y: p.lat
  405. };
  406. reverseLocation($scope.geoCode, null, function(address) {
  407. $scope.address = address;
  408. ariaz(address, function(result) {
  409. //console.log('ariaz', result);
  410. });
  411. getResults();
  412. });
  413. });
  414. };
  415. var ariaz = function(address, callback) {
  416. var url = 'http://www.eligibilite-adsl.com/testXmlAriase.php?ip=80.13.25.43&insee=35238&rivoli=8993&numeroVoie=2&complementNumeroVoie=';
  417. $.get(
  418. url,
  419. function(data, status) {
  420. callback(data);
  421. });
  422. };
  423. var computeDateFTTH = function() {
  424. if(!$scope.results.ftth) {return;}
  425. // A date already exists
  426. if($scope.results.ftth.DATE_OUV_SERVICE_REEL || $scope.results.ftth.DATE_OUV_SERVICE_PREV) {
  427. $scope.results.ftth.date = $scope.results.ftth.DATE_OUV_SERVICE_REEL || $scope.results.ftth.DATE_OUV_SERVICE_PREV;
  428. return;
  429. }
  430. // Compute Date
  431. var momentDate = moment($scope.results.ftth.DATE_FIN_TRAV_PREV, 'DD/MM/YY');
  432. momentDate.add(nbJoursFTTH, 'days');
  433. $scope.results.ftth.date = momentDate.format('DD/MM/YYYY');
  434. };
  435. var computeFullAdress = function() {
  436. return $scope.result.eligibilite.complement_addresse;
  437. };
  438. var formatDate = function(value) {
  439. return moment(value.toString().substr(0,4) + '-' + value.toString().substr(4,2) + '-' + value.toString().substr(6,2)).locale("fr");
  440. };
  441. var getRecordsFor = function(identifier, coordinates) {
  442. var records = [];
  443. _.each($scope.data[identifier], function(record) {
  444. _.some(record._polygons, function(polygon) {
  445. if(isInside(polygon, coordinates)) {
  446. records.push(record);
  447. return true;
  448. }
  449. });
  450. });
  451. // Debug
  452. var debug = false;
  453. if (debug) {
  454. var colors = ['red', 'green', 'blue', 'black', 'silver', 'yellow'];
  455. var marker = L.marker([coordinates.y, coordinates.x]).addTo(map);
  456. var Lpolygons = [];
  457. _.each(records, function(record, i) {
  458. var style = {
  459. color : colors[i],
  460. fillColor: colors[i],
  461. weight : 4
  462. };
  463. _.each(record._polygons, function(polygon) {
  464. Lpolygons.push(L.polygon(polygon, style).bindPopup($scope.getHtmlContent(identifier, record)));
  465. });
  466. });
  467. L.layerGroup(Lpolygons).addTo(map);
  468. }
  469. return records;
  470. };
  471. var getResults = function() {
  472. $scope.results = {};
  473. $.ajax({
  474. method : "POST",
  475. url : "ajax/oracle.php",
  476. data : $scope.geoCode
  477. })
  478. .error(function(err) {
  479. console.error('Oracle issue', err);
  480. // Debug without Oracle access
  481. onResults('{"x":-1.1060984089996,"y":49.119046582,"ftth":[{"ID_ZAPM_PARTIELLE":"203AP0","DATE_OUV_SERVICE_REEL":null,"DATE_OUV_SERVICE_PREV":null,"DATE_FIN_TRAV_PREV":"02\/05\/16"}],"adsl":[{"ID_FT_ADSL":"656","LEGENDE":"TV sur ADSL","NATURE":"0 - 37"}],"mimo":null}');
  482. })
  483. .done(function( msg ) {
  484. onResults(msg);
  485. });
  486. var onResults = function(results) {
  487. try {
  488. $scope.results = JSON.parse(results);
  489. $scope.results.address = $scope.address;
  490. $scope.results.ftth = parseResults($scope.results.ftth);
  491. $scope.results.adsl = parseResults($scope.results.adsl);
  492. $scope.results.mimo = parseResults($scope.results.mimo);
  493. computeDateFTTH();
  494. }
  495. catch(e) {
  496. console.error(e);
  497. }
  498. console.log('$scope.results', $scope.results);
  499. };
  500. $scope.$evalAsync();
  501. };
  502. var init = function() {
  503. var stlo = [49.1154686, -1.0828136000000086];
  504. var map = L.map('map', {zoomControl:false}).setView(stlo, 9);
  505. map.on('dblclick', function(e) {
  506. var p = e.latlng;
  507. //console.log('click', e.latlng); // e is an event object (MouseEvent in this case)
  508. $scope.geoCode = {
  509. x: p.lng,
  510. y: p.lat
  511. };
  512. addCurrentMarker();
  513. $scope.showResultPane();
  514. getResults();
  515. });
  516. var maps = {
  517. "carte" : 'http://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}',
  518. "satellite" : 'http://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}'
  519. };
  520. var cLayer = L.tileLayer(maps.satellite, {
  521. attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
  522. maxZoom: 18
  523. }).addTo(map);
  524. var styleOpts = {
  525. color : 'red',
  526. fillColor: 'red',
  527. weight : 8
  528. };
  529. $scope.data = {};
  530. $scope.colors = {
  531. "ftth": "#8cc474", // green
  532. "mimo": "#f9b256", // orange
  533. "adsl": "#76a7fa" // blue
  534. };
  535. $http({method: 'POST', url: 'data/dictionary.json'}).success(function(data) {
  536. $scope.dictionary = data;
  537. });
  538. $http({method: 'POST', url: 'data/Contour_Manche.json'}).success(function(data) {
  539. var style = {
  540. color : 'blue',
  541. fillColor: 'blue',
  542. weight : 2
  543. };
  544. $scope.data.manche = [{
  545. _polygons : [data.features[0].geometry.coordinates[0]],
  546. _style : style,
  547. _properties : {
  548. name : {string: 'Manche'}
  549. }
  550. }];
  551. var mancheCoordinates = data && data.features && data.features[0] && data.features[0].geometry && data.features[0].geometry.coordinates && data.features[0].geometry.coordinates[0]; // response data
  552. _.each(mancheCoordinates, function(c, i) {
  553. mancheCoordinates[i] = [c[1], c[0]];
  554. });
  555. // Rectangle coordinates around Manche
  556. //var mancheCoordinates = [[49.732307856286, -1.97117692088061],[48.4, -1.75],[48.4, -0.5],[49.732307856286, -1.2]];
  557. // Debug: show manche limits
  558. //L.polygon(mancheCoordinates, {color: 'blue', fillColor: 'blue',weight: 8}).addTo(map);
  559. searchExtent = {
  560. "xmin" : _.max(_.map(mancheCoordinates, function(c) {return c[1];})),
  561. "ymin" : _.max(_.map(mancheCoordinates, function(c) {return c[0];})),
  562. "xmax" : _.min(_.map(mancheCoordinates, function(c) {return c[1];})),
  563. "ymax" : _.min(_.map(mancheCoordinates, function(c) {return c[0];})),
  564. "spatialReference" : {"wkid" : 84}
  565. };
  566. var suggestURL = 'https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/suggest?f=pjson&searchExtent=' + JSON.stringify(searchExtent);
  567. $scope.suggestLocation = function(val) {
  568. console.log('__suggestLocation', val);
  569. return $http.get(suggestURL, {
  570. params: {
  571. text: val
  572. }
  573. }).then(function(response){
  574. $scope.suggestions = response.data.suggestions;
  575. console.log('__suggestLocation response', response);
  576. return response.data.suggestions.map(function(item){
  577. return item.text;
  578. });
  579. });
  580. };
  581. });
  582. //console.time('FTTH data');
  583. $http({method: 'POST', url: 'data/FTTH_zapm_partielle.json'}).success(function(data) {
  584. var style = {
  585. color : $scope.colors.ftth,
  586. fillColor: $scope.colors.ftth,
  587. weight : 2
  588. };
  589. var properties = {
  590. name : {key: 'ATD'},
  591. hidden: ['ID_PM', 'MARCHE', 'ID_FT_ADSL', 'ID_FTTH_MN_ZAPM_PARTIELLE', 'ID_ZAPM_PARTIELLE', 'ID_ZAPM'],
  592. position: ['DATE_DEB_TRAV_PREV']
  593. };
  594. parseData('ftth', data, style, properties);
  595. //console.timeEnd('FTTH data');
  596. //console.debug('Data for FTTH are ready', data);
  597. if($scope.data.mimo && $scope.data.adsl && $scope.data.ftth) {
  598. $scope.loaded = true;
  599. }
  600. $scope.$evalAsync();
  601. });
  602. //console.time('ADSL data');
  603. $http({method: 'POST', url: 'data/TEL_FT_ADSL.json'}).success(function(data) {
  604. var style = {
  605. color : $scope.colors.adsl,
  606. fillColor: $scope.colors.adsl,
  607. weight : 2
  608. };
  609. var properties = {
  610. name : {key: 'LEGENDE'},
  611. hidden: ['NATURE', 'NRA_CETE', 'NRA_TMP', 'NRA_DPT', 'ID_FT_ADSL']
  612. };
  613. parseData('adsl', data, style, properties);
  614. //console.timeEnd('ADSL data');
  615. //console.debug('Data for ADSL are ready', data);
  616. if($scope.data.mimo && $scope.data.adsl && $scope.data.ftth) {
  617. $scope.loaded = true;
  618. }
  619. $scope.$evalAsync();
  620. });
  621. //console.time('MiMo data');
  622. $http({method: 'POST', url: 'data/Couverture_mimo.json'}).success(function(data) {
  623. var style = {
  624. color : $scope.colors.mimo,
  625. fillColor: $scope.colors.mimo,
  626. weight : 2
  627. };
  628. var properties = {
  629. name : {string: 'Couverture MiMo'},
  630. hidden: ['ID_MIMO_COUVERTURE']
  631. };
  632. parseData('mimo', data, style, properties);
  633. //console.timeEnd('MiMo data');
  634. //console.debug('Data for MIMO are ready', data);
  635. if($scope.data.mimo && $scope.data.adsl && $scope.data.ftth) {
  636. $scope.loaded = true;
  637. }
  638. $scope.$evalAsync();
  639. });
  640. window.map = map;
  641. $scope.mapType = 'Satellite';
  642. $scope.view = {};
  643. $scope.isShown = {};
  644. };
  645. var isDate = function(value) {
  646. return (value.toString().length === 14 && value.toString().substring(0,2) === "20");
  647. };
  648. var isInside = function(polygon, point) {
  649. // ray-casting algorithm based on
  650. // http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
  651. var y = point.x ? point.x : point[0],
  652. x = point.y ? point.y : point[1];
  653. var inside = false;
  654. for (var i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
  655. var xi = polygon[i][0], yi = polygon[i][1];
  656. var xj = polygon[j][0], yj = polygon[j][1];
  657. var intersect = ((yi > y) != (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
  658. if (intersect) {
  659. inside = !inside;
  660. }
  661. }
  662. return inside;
  663. };
  664. var parseData = function(identifier, data, style, properties) {
  665. var getPolygonsCoord = function(type, coord) {
  666. var result = [];
  667. if(type === 'Polygon') {
  668. result.push(_.map(coord[0], function(r) {return [r[1], r[0]];}));
  669. }
  670. if(type === 'MultiPolygon') {
  671. var p = [];
  672. _.each(coord, function(c) {
  673. result.push(_.map(c[0], function(r) {return [r[1], r[0]];}));
  674. });
  675. }
  676. return result;
  677. };
  678. var records = [];
  679. _.each(data.features, function(r) {
  680. var record = r.properties;
  681. var polygons = getPolygonsCoord(r.geometry.type, r.geometry.coordinates);
  682. record._coordinates = r.geometry.coordinates;
  683. record._type = r.geometry.type;
  684. record._polygons = polygons;
  685. record._style = style;
  686. record._properties = properties;
  687. records.push(record);
  688. });
  689. $scope.data[identifier] = records;
  690. };
  691. var parseResults = function(records) {
  692. if(!records || !records.length) {
  693. return null;
  694. }
  695. if(records.length === 1) {
  696. return records[0];
  697. }
  698. var result = records[0];
  699. return result;
  700. };
  701. var reverseLocation = function(geoCode, address, callback) {
  702. var reverseGeo = 'http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/reverseGeocode?f=pjson&distance=300';
  703. var url = reverseGeo + '&location=' + (geoCode ? $scope.geoCode.x + ',' + $scope.geoCode.y : address) ;
  704. $.get(
  705. url,
  706. function(data, status) {
  707. data = JSON.parse(data);
  708. var adresse = data && data.address && data.address.Match_addr;
  709. if(data && data.address && data.address.Address) {
  710. var i = 0;
  711. var num = '';
  712. while(!isNaN(parseInt(data.address.Address[i], 10))) {
  713. num += data.address.Address[i];
  714. i++;
  715. }
  716. data.address.StreetNumber = num;
  717. data.address.Address = data.address.Address.substr(num.length).trim();
  718. var typeVoie = data.address.Address.substring(0, data.address.Address.indexOf(' ')).toLowerCase();
  719. type = _.find(catTypeVoie, function(c){
  720. if(c.id === typeVoie || c.name.toLowerCase() === typeVoie) {
  721. return true;
  722. }
  723. });
  724. if(type) {
  725. data.address.StreetType = type.id;
  726. data.address.Address = data.address.Address.substr(typeVoie.length).trim();
  727. }
  728. }
  729. if(adresse)
  730. console.debug('Reverse', geoCode, address, '=>', adresse, data.address);
  731. callback(adresse, data.address);
  732. $scope.$evalAsync();
  733. });
  734. };
  735. $scope.changeMap = function(value) {
  736. //console.log('Goto', value);
  737. map.removeLayer(cLayer);
  738. cLayer = L.tileLayer(maps[value], {
  739. attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
  740. maxZoom: 18
  741. }).addTo(map);
  742. };
  743. $scope.closeRight = function() {
  744. $mdSidenav('right').close().then(function(){});
  745. };
  746. $scope.computeLayer = function(identifier) {
  747. var Lpolygons = [];
  748. _.each($scope.data[identifier], function(record) {
  749. _.each(record._polygons, function(polygon) {
  750. Lpolygons.push(L.polygon(polygon, record._style).bindPopup($scope.getHtmlContent(identifier, record)));
  751. });
  752. });
  753. layer[identifier] = L.layerGroup(Lpolygons);
  754. };
  755. $scope.formatDateFTTH = function(date) {
  756. if(!date) {return;}
  757. var momentDate = moment(date, 'DD/MM/YYYY');
  758. var result = '<div class="popup-line"><div class="box-eligibilite-title">Date prévisionnelle abonnement FTTH</div><div style="font-weight: bold;" class="popup-value">' + momentDate.locale("fr").format('ddd, LL') + '</div><div class="popup-small-date">' + momentDate.locale("fr").fromNow() + '</div></div>';
  759. return $sce.trustAsHtml(result);
  760. };
  761. $scope.formatResults = function(identifier, results) {
  762. return $sce.trustAsHtml($scope.getHtmlContent(identifier, results));
  763. };
  764. $scope.getGeoCode = function(address, magicKey, callback) {
  765. var findURL = 'https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/find?f=pjson&searchExtent=' + JSON.stringify(searchExtent);
  766. getGeoCodeInProgress = true;
  767. var url = findURL + "&text=" + address + ((magicKey) ? ("&magicKey=" + magicKey) : ', Basse-Normandie, France');
  768. //console.log('url', url);
  769. $.get(
  770. url,
  771. function(data, status) {
  772. data = JSON.parse(data);
  773. console.debug('address, magicKey', address, magicKey, data);
  774. if (status === 'success' && data.locations[0]) {
  775. if(data.locations[0].extent.xmax < searchExtent.xmin &&
  776. data.locations[0].extent.xmax > searchExtent.xmax &&
  777. data.locations[0].extent.xmin > searchExtent.xmax &&
  778. data.locations[0].extent.xmin > searchExtent.xmax) {
  779. getGeoCodeInProgress = false;
  780. console.debug('getGeoCode', address, magicKey, '=>', data);
  781. return callback(null, data);
  782. }
  783. getGeoCodeInProgress = false;
  784. console.debug('getGeoCode', address, magicKey, '=>', 'No result');
  785. callback('No result for ' + address);
  786. } else {
  787. getGeoCodeInProgress = false;
  788. console.debug('getGeoCode', address, magicKey, '=>', 'No result');
  789. callback(status !== 'success' ? status : 'No result for ' + address);
  790. }
  791. });
  792. };
  793. $scope.getHtmlContent = function(identifier, record) {
  794. var title = record._properties.name.string ? record._properties.name.string : record[record._properties.name.key];
  795. // Tooltip content
  796. var tooltip = '<div class="popup-line"><span class="popup-title">' + title +'</span></div>' +
  797. '<hr>';
  798. _.each(record, function(value, property) {
  799. if(property.charAt(0) === '_' ||
  800. (record._properties.hidden && record._properties.hidden.indexOf(property) !== -1) ||
  801. record._properties.name.key === property ||
  802. value === null |
  803. typeof value === 'undefined') {
  804. return;
  805. }
  806. var label = $scope.dictionary[property] || property;
  807. value = $scope.dictionary[value] || value;
  808. var date;
  809. if(property.substring(0, 5) === 'DATE_' && !$scope.dictionary[value] && isDate(value)) {
  810. date = formatDate(value);
  811. }
  812. tooltip += '<div class="popup-line"><div class="popup-label">' + label + '</div><div class="popup-value">' + (date ? date.locale("fr").format('ddd, LL') : value) + '</div><div class="popup-small-date">' + (date ? date.locale("fr").fromNow() : '') + '</div></div>';
  813. });
  814. return tooltip;
  815. };
  816. $scope.hideLayer = function(identifier) {
  817. map.removeLayer(layer[identifier]);
  818. };
  819. $scope.hideResultPane = function() {
  820. if(!$('#result').height()) {return;}
  821. $('#result').animate({height: 0}, 1000);
  822. $('#map').animate({
  823. height: $('body').height(),
  824. }, 1000, function() {
  825. // Animation complete.
  826. map.invalidateSize();
  827. var centerPoint = $scope.geoCode ? new L.LatLng($scope.geoCode.y, $scope.geoCode.x) : stlo;
  828. map.setView(centerPoint, 14);
  829. });
  830. };
  831. $scope.initPopup = function() {
  832. //console.log('initPopup', $scope.geoCode);
  833. $scope.postForm = null;
  834. reverseLocation($scope.geoCode, null, function(string, address) {
  835. //console.log('add', address);
  836. $scope.result = {eligibilite: {}};
  837. // Debug
  838. // $scope.result.eligibilite.prenom = 'Francois';
  839. // $scope.result.eligibilite.nom = 'Beaufils';
  840. // $scope.result.eligibilite.email = 'francoisbeaufils@zeno-labs.com';
  841. // $scope.result.eligibilite.vous_etes = 'locataire';
  842. // $scope.result.eligibilite.ce_logement_est = 'residence_principale';
  843. // $scope.result.eligibilite.info_et_libertes = true;
  844. // $scope.result.eligibilite.accord = true;
  845. $scope.result.eligibilite.geo_code = JSON.stringify($scope.geoCode);
  846. $scope.result.eligibilite.code_postal = address.Postal;
  847. $scope.result.eligibilite.complement_addresse = address.Match_addr;
  848. $scope.result.eligibilite.nom_voie = address.Address;
  849. $scope.result.eligibilite.numero_voie = address.StreetNumber;
  850. $scope.result.eligibilite.type_voie = address.StreetType;
  851. $scope.result.eligibilite.ville = address.City;
  852. });
  853. };
  854. $scope.isFormValid = function() {
  855. if(!$scope.result || !$scope.result.eligibilite) {return;}
  856. var isValid = true;
  857. _.each($scope.formulaires.eligibilite.sections, function(section) {
  858. _.each(section.lines, function(line) {
  859. _.each(line.ctrls, function(ctrl) {
  860. ctrl.invalid = false;
  861. if(ctrl.require && !ctrl.isValid($scope.result.eligibilite[ctrl.id])) {
  862. isValid = false;
  863. ctrl.invalid = true;
  864. }
  865. });
  866. });
  867. });
  868. return isValid;
  869. };
  870. $scope.onSubmitAddress = function($item, $model, $label) {
  871. console.log('onSubmitAddress address', $scope.address);
  872. console.log('onSubmitAddress $item', $item);
  873. console.log('onSubmitAddress $model', $model);
  874. console.log('onSubmitAddress $label', $label);
  875. // Get magic key
  876. var item = _.find($scope.suggestions, {text: $item});
  877. $scope.magicKey = item.magicKey;
  878. console.log('onSubmitAddress -_-item', item, '=>', $scope.magicKey);
  879. $scope.getGeoCode($scope.address, $scope.magicKey, function(err, data) {
  880. $scope.geoCode = data && data.locations && data.locations[0] && data.locations[0].feature.geometry;
  881. if(err) {console.error('Geocode error', err);}
  882. var toast = toast || {
  883. template: '<md-toast><i class = " md-error"></i> Oups! Aucun résultat trouvé dans la Manche pour: ' + $scope.address + '</md-toast>',
  884. hideDelay: 3000,
  885. position: 'bottom right'
  886. };
  887. // $mdToast.simple()
  888. // .template(')
  889. // .position('bottom right')
  890. // .hideDelay(3000);
  891. if(err || !$scope.geoCode) {
  892. $scope.hideResultPane();
  893. $mdToast.show(toast);
  894. }
  895. //console.log('Addresses found for', $scope.address, '=>', data, '=> Geocode:', $scope.geoCode);
  896. if($scope.geoCode) {
  897. addCurrentMarker();
  898. $scope.showResultPane();
  899. getResults();
  900. }
  901. });
  902. };
  903. $scope.postFormEl = function() {
  904. $scope.postForm = {inProgress: true};
  905. //console.log('postForm', $scope.result.eligibilite);
  906. $scope.$evalAsync();
  907. function mysql_real_escape_string (str) {
  908. if(typeof str !== 'string') {return str;}
  909. return str.replace(/[\0\x08\x09\x1a\n\r"'\\\%]/g, function (char) {
  910. switch (char) {
  911. case "\0":
  912. return "\\0";
  913. case "\x08":
  914. return "\\b";
  915. case "\x09":
  916. return "\\t";
  917. case "\x1a":
  918. return "\\z";
  919. case "\n":
  920. return "\\n";
  921. case "\r":
  922. return "\\r";
  923. case "\"":
  924. case "'":
  925. case "\\":
  926. case "%":
  927. return "\\"+char; // prepends a backslash to backslash, percent,
  928. // and double/single quotes
  929. }
  930. });
  931. }
  932. var keys = '';
  933. var values = '';
  934. _.each($scope.result.eligibilite, function(value, key) {
  935. keys += '`' + key + '`, ';
  936. values += "'" + mysql_real_escape_string(value) + "', ";
  937. });
  938. var query = "INSERT INTO `eligibilite`.`demandes` (" + keys.substring(0, keys.length -2) + ") VALUES (" + values.substring(0, values.length -2) + ");";
  939. //console.log('query', query);
  940. $.ajax({
  941. method : "POST",
  942. url : "ajax/datastores.php",
  943. data : {query: query}
  944. })
  945. .done(function( msg ) {
  946. if(!isNaN(msg)) {
  947. $scope.postForm = {ok: true};
  948. var numDemande = moment().format('YYYYMMDD') + msg;
  949. var body = 'Bonjour ' + $scope.result.eligibilite.prenom + ' ' + $scope.result.eligibilite.nom + ', <br>' +
  950. 'Nous vous confirmons votre demande de pré-raccordement FTTH. <br><br>' +
  951. 'Cette demande porte le numéro: ' +
  952. '<span style="color: #31708f;font-size:17px; font-weight:bold;">' + numDemande + '</span><br><br>' +
  953. 'Voici le détail de votre demande:' +
  954. '<div style="color: #31708f;background-color: #d9edf7;border-color: #bce8f1;padding: 10px;margin: 1em;font-size:14px;">' +
  955. '<table style="line-height: 40px;">';
  956. // _.each($scope.result.eligibilite, function(value, key) {
  957. // body += '<tr>';
  958. // body += '<th style="text-align:left;">' + key + '</th>';
  959. // body += '<td>' + value + '</td>';
  960. // body += '</tr>';
  961. // });
  962. // Numero demande
  963. body += '<tr>';
  964. body += '<th style="text-align: left;white-space: nowrap;height: 40px;color: #666;">Numéro demande</th>';
  965. body += '<td>' + numDemande + '</td>';
  966. body += '</tr>';
  967. // Date demande
  968. body += '<tr>';
  969. body += '<th style="text-align: left;white-space: nowrap;height: 40px;color: #666;">Date</th>';
  970. body += '<td>' + moment().lang('fr').format('LLLL') + '</td>';
  971. body += '</tr>';
  972. // Demandeur
  973. body += '<tr>';
  974. body += '<th style="text-align: left;white-space: nowrap;height: 40px;color: #666;">Demandeur</th>';
  975. body += '<td>' + $scope.result.eligibilite.prenom + ' ' + $scope.result.eligibilite.nom + '</td>';
  976. body += '</tr>';
  977. // Email
  978. body += '<tr>';
  979. body += '<th style="text-align: left;white-space: nowrap;height: 40px;color: #666;">Email</th>';
  980. body += '<td>' + $scope.result.eligibilite.email + '</td>';
  981. body += '</tr>';
  982. // Adresse
  983. body += '<tr>';
  984. body += '<th style="text-align: left;white-space: nowrap;height: 40px;color: #666;">Adresse</th>';
  985. body += '<td>' + computeFullAdress() + '</td>';
  986. body += '</tr>';
  987. // Vous etes
  988. var cat = _.find(catVousEtes, {id: $scope.result.eligibilite.vous_etes});
  989. var res = cat && cat.name ? cat.name : $scope.result.eligibilite.vous_etes;
  990. body += '<tr>';
  991. body += '<th style="text-align: left;white-space: nowrap;height: 40px;color: #666;">Vous êtes</th>';
  992. body += '<td>' + res + '</td>';
  993. body += '</tr>';
  994. // Ce logement est
  995. var cat2 = _.find(catCeLogementEst, {id: $scope.result.eligibilite.ce_logement_est});
  996. var res2 = cat2 && cat2.name ? cat2.name : $scope.result.eligibilite.ce_logement_est;
  997. body += '<tr>';
  998. body += '<th style="text-align: left;white-space: nowrap;height: 40px;color: #666;">Ce logement est</th>';
  999. body += '<td>' + res2 + '</td>';
  1000. body += '</tr>';
  1001. //console.log('$scope.result', $scope.result);
  1002. body += '</table></div><br>';
  1003. body += 'Conformément à la loi "informatique et libertés" du 6 janvier 1978 modifiée, vous bénéficiez d’un droit d’accès, de rectification aux informations qui vous concernent, d’opposition au traitement de vos données personnelles. Si vous souhaitez exercer ce droit et obtenir communication des informations vous concernant, merci de nous contacter :' + '<br>' +
  1004. '<div style="">' +
  1005. ' Email: ' + siteEmail + '<br>' +
  1006. ' Adresse: ' + siteAddresse + '<br>' +
  1007. '</div><br><br>';
  1008. body += 'A bientôt sur: <a href="' + siteUrl + '">' + siteName + '</a>';
  1009. var mail = {
  1010. to : $scope.result.eligibilite.email,
  1011. sujet : 'Votre demande de pré-raccordement FTTH n° ' + numDemande,
  1012. message: body
  1013. };
  1014. $.ajax({
  1015. method : "POST",
  1016. url : "ajax/datastores.php",
  1017. data : {mail: mail}
  1018. })
  1019. .done(function( msg ) {
  1020. console.log('Mail result', msg);
  1021. });
  1022. $scope.result.eligibilite = {};
  1023. }
  1024. else {
  1025. $scope.postForm = {error: msg};
  1026. }
  1027. $scope.$apply();
  1028. });
  1029. };
  1030. $scope.showLayer = function(identifier) {
  1031. map.addLayer(layer[identifier]);
  1032. };
  1033. $scope.showResultPane = function() {
  1034. var bodyHeight = $('body').height();
  1035. var height = Math.max(300, bodyHeight / 3);
  1036. var heightMap = bodyHeight - height;
  1037. $('#result').animate({height: height + 'px'}, 1000);
  1038. $('#map').animate({
  1039. height: heightMap + 'px',
  1040. }, 1000, function() {
  1041. // Animation complete.
  1042. map.invalidateSize();
  1043. map.setView(new L.LatLng($scope.geoCode.y, $scope.geoCode.x), 14);
  1044. });
  1045. };
  1046. $scope.toggleResultPane = function() {
  1047. if($('#result').height()) {
  1048. return $scope.hideResultPane();
  1049. }
  1050. if($scope.results && $scope.results.ftth) {
  1051. return $scope.showResultPane();
  1052. }
  1053. };
  1054. $scope.toggleRight = function() {
  1055. $mdSidenav('right').toggle()
  1056. .then(function(){});
  1057. };
  1058. $scope.$watch('view', function(view) {
  1059. if(_.isEmpty(view)) {return;}
  1060. $('#layer-loading').removeClass('force-hidden').find('.md-inner').show();
  1061. setTimeout(function() {
  1062. _.each(view, function(value, key) {
  1063. if($scope.isShown[key] !== value) {
  1064. if(value) {
  1065. if(typeof $scope.isShown[key] !== 'undefined') {
  1066. $scope.showLayer(key);
  1067. $('#layer-loading').find('.md-inner').hide();
  1068. }
  1069. else {
  1070. $timeout(function() {
  1071. $scope.computeLayer(key);
  1072. $scope.showLayer(key);
  1073. $('#layer-loading').find('.md-inner').hide();
  1074. }, 500);
  1075. }
  1076. }
  1077. else {
  1078. $scope.hideLayer(key);
  1079. setTimeout(function() {
  1080. $('#layer-loading').find('.md-inner').hide();
  1081. }, 1000);
  1082. }
  1083. $scope.isShown[key] = value;
  1084. }
  1085. });
  1086. });
  1087. }, true);
  1088. $(window).resize(function() {
  1089. if(!$('#result').height()) {return;}
  1090. $scope.showResultPane();
  1091. });
  1092. init();
  1093. });