Advertisement
newArray

bco

Sep 26th, 2019
519
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { Component, ViewChild, OnInit, AfterContentInit } from '@angular/core';
  2. import { NavController, ToastController, LoadingController } from 'ionic-angular';
  3.  
  4. import { Geolocation } from '@ionic-native/geolocation';
  5. declare var google;
  6.  
  7. import { Http }  from "@angular/http";
  8. import "rxjs/add/operator/map";
  9. import 'rxjs/add/operator/toPromise';
  10. import 'rxjs/Observable';
  11.  
  12. @Component({
  13.   selector: 'page-laporan',
  14.   templateUrl: 'laporan.html'
  15. })
  16. export class LaporanPage implements OnInit, AfterContentInit{
  17.   // api_url: string = 'https://clean-troops.000webhostapp.com/api/';
  18.   // api_url: string = 'http://localhost/clean_api/';
  19.   dataLaporan: any
  20.   map: any
  21.   @ViewChild('mapElement') mapElement;
  22.   latitude: any
  23.   longitude: any
  24.   no_tps: string
  25.   keterangan: string
  26.   // api_url: string = 'http://localhost/clean_api/';
  27.   api_url: string = 'http://clean-troops.000webhostapp.com/api/';
  28.   markersData: any
  29.   searching = false
  30.   titikAwal:any = {
  31.     'latitude': -3.989146,
  32.     'longitude': 122.468892,
  33.     'marker': 'TPA'
  34.   }
  35.   jumlahLebah: number
  36.   allPaths:any = []
  37.   jaraks:any = []
  38.   shortPath = 99999
  39.  
  40.   constructor(
  41.     public navCtrl: NavController,
  42.     public http: Http,
  43.     public geolocation: Geolocation,
  44.     public toastCtrl: ToastController,
  45.     public loadingCtrl: LoadingController
  46.   ) {
  47.     this.http.get(this.api_url + 'getLaporan.php').subscribe(async data => {
  48.       let temp = await JSON.parse(data['_body']);
  49.       this.dataLaporan = await temp['server_response'];
  50.       console.log(this.dataLaporan)
  51.     }, err=> {
  52.       console.log(err)
  53.     });
  54.   }
  55.  
  56.   randomNumber(){
  57.     return Math.floor(Math.random() * (this.dataLaporan.length - 1) + 1)
  58.   }
  59.  
  60.   BCO(){
  61.     this.allPaths = new Array()
  62.     for (let i = 0; i < this.jumlahLebah; i++) {
  63.       const allPoints = [
  64.         {'x':'A', 'y':0},
  65.         {'x':'B', 'y':1},
  66.         {'x':'C', 'y':2},
  67.         {'x':'D', 'y':3},
  68.         {'x':'E', 'y':4},
  69.         {'x':'F', 'y':5},
  70.         {'x':'G', 'y':6},
  71.         {'x':'H', 'y':7},
  72.         {'x':'I', 'y':8},
  73.         {'x':'J', 'y':9},
  74.         {'x':'K', 'y':10},
  75.         {'x':'L', 'y':11},
  76.         {'x':'M', 'y':12},
  77.         {'x':'N', 'y':13},
  78.         {'x':'O', 'y':14},
  79.         {'x':'P', 'y':15}
  80.       ];
  81.  
  82.       for (let i = 0; i < allPoints.length; i++) {
  83.           if(allPoints[i]['x']==this.titikAwal['marker']){
  84.               allPoints.splice(i,1)
  85.           }
  86.       }
  87.  
  88.       this.titikAwalFunc(allPoints);
  89.     }
  90.  
  91.     console.log(this.allPaths)
  92.   }
  93.  
  94.   async titikAwalFunc(points){
  95.     this.http.get(this.api_url + 'getLaporan.php').subscribe(data => {
  96.       let temp = JSON.parse(data['_body']);
  97.       this.markersData = temp['server_response'];
  98.  
  99.       console.log(points)
  100.       let newPath = new Array()
  101.       let pl = points.length
  102.  
  103.       for (let i = 0; i < pl; i++) {
  104.         let rand = Math.floor(Math.random() * (points.length))
  105.         // newPath.push(points[rand])
  106.         for(let key in this.markersData) {
  107.           // if(this.markersData[key]['marker']==this.titikAwal['marker']){
  108.           //   this.markersData.splice(key, 1)
  109.           // }
  110.  
  111.           if(this.markersData[key]['marker']==points[rand]['x']){
  112.             newPath.push(this.markersData[key]['marker'])
  113.             // console.log(this.markersData[key]['marker'])
  114.           }
  115.         }
  116.  
  117.         let cut = points.splice(rand, 1)
  118.       }
  119.  
  120.       this.setRoutesMap(newPath, this.allPaths.length)
  121.       this.allPaths.push(newPath)
  122.     }, err=> {
  123.       console.log(err)
  124.     });
  125.   }
  126.  
  127.   haversineDistance(lon1, lat1, lon2, lat2){
  128.     function toRad(x) {
  129.       return x * Math.PI / 180;
  130.     }
  131.  
  132.     // lon1 = -3.985462;
  133.     // lat1 = 122.496236;
  134.     //
  135.     // lon2 = -3.971944;
  136.     // lat2 = 122.506407;
  137.  
  138.     var R = 6371; // Earth’s mean radius in meter
  139.     var dLat = toRad(lat2 - lat1);
  140.     var dLong = toRad(lon2 - lon1);
  141.     var a =
  142.       Math.sin(dLat / 2) * Math.sin(dLat / 2) +
  143.       Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) *
  144.       Math.sin(dLong / 2) * Math.sin(dLong / 2);
  145.  
  146.     var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  147.     var d = R * c;
  148.     d /= 1.60934;
  149.     d = Math.round(d * 100) / 100
  150.     return d; // returns the distance in km
  151.   }
  152.  
  153.   reorderObject(data){
  154.     let newMarkerObj = new Array()
  155.     for(let key in this.markersData){
  156.       newMarkerObj[this.markersData[key]['marker']] = this.markersData[key]
  157.     }
  158.  
  159.     return newMarkerObj
  160.   }
  161.  
  162.   setRoutesMap(data, i){
  163.     console.log(data)
  164.     let start_lat = this.titikAwal['latitude'];
  165.     let start_lng = this.titikAwal['longitude'];
  166.  
  167.     let newMarkerObj = this.reorderObject(this.markersData)
  168.  
  169.     let newRoutesWaypoints = new Array()
  170.  
  171.     for(let i = 0; i < data.length; i++) {
  172.         newRoutesWaypoints.push(newMarkerObj[data[i]])
  173.     }
  174.  
  175.     let finish_lat = newRoutesWaypoints[Object.keys(newRoutesWaypoints).length-1]['latitude'];
  176.     let finish_lng = newRoutesWaypoints[Object.keys(newRoutesWaypoints).length-1]['longitude'];
  177.  
  178.     let waypoints = [];
  179.  
  180.     let prevMarker = this.titikAwal['marker']
  181.     let prevRouteLat = start_lat
  182.     let prevRouteLng = start_lng
  183.  
  184.     let jarak
  185.     let totalJarak = 0
  186.  
  187.     for (var key in newRoutesWaypoints) {
  188.       if (data.hasOwnProperty(key)) {
  189.         waypoints.push({
  190.           location: new google.maps.LatLng(newRoutesWaypoints[key]['latitude'], newRoutesWaypoints[key]['longitude']),
  191.           stopover: true
  192.         });
  193.  
  194.         //hitung jarak
  195.         jarak = this.haversineDistance(
  196.           prevRouteLat,
  197.           prevRouteLng,
  198.           newRoutesWaypoints[key]['latitude'],
  199.           newRoutesWaypoints[key]['longitude']
  200.         );
  201.  
  202.         console.log(prevMarker+ " -> "+ newRoutesWaypoints[key]['marker'] +' : '+jarak+' km')
  203.         totalJarak+=jarak;
  204.  
  205.         prevMarker = newRoutesWaypoints[key]['marker']
  206.         prevRouteLat = newRoutesWaypoints[key]['latitude']
  207.         prevRouteLng = newRoutesWaypoints[key]['longitude']
  208.  
  209.       }
  210.     }
  211.  
  212.     jarak = this.haversineDistance(
  213.       prevRouteLat,
  214.       prevRouteLng,
  215.       this.titikAwal['latitude'],
  216.       this.titikAwal['longitude']
  217.     );
  218.  
  219.     totalJarak+=jarak
  220.  
  221.     console.log(prevMarker+ " -> "+ this.titikAwal['marker'] +' : '+jarak+' km')
  222.  
  223.     waypoints.push({
  224.       location: new google.maps.LatLng(this.titikAwal['latitude'], this.titikAwal['longitude']),
  225.       stopover: true
  226.     });
  227.  
  228.  
  229.     totalJarak+=Math.round(jarak * 100) / 100;
  230.     let prevPath = this.shortPath
  231.     this.shortPath = totalJarak<=prevPath ? totalJarak : this.shortPath
  232.     this.jaraks[i] = totalJarak
  233.     console.log('Total Jarak : '+totalJarak+' km')
  234.  
  235.     var directionsService = new google.maps.DirectionsService(),
  236.       directionsDisplay = new google.maps.DirectionsRenderer({
  237.         suppressMarkers: true
  238.       }),
  239.       displayRoute = function() {
  240.         directionsService.route({
  241.           origin: new google.maps.LatLng(start_lat, start_lng), // Pass this in place of the address 'Akin Ogunlewe street VI'
  242.           destination: new google.maps.LatLng(finish_lat, finish_lng), // Pass this in place of the address 'Falolu road Surulere'
  243.           waypoints: waypoints,
  244.           travelMode: google.maps.TravelMode.DRIVING
  245.         }, function(response, status) {
  246.           if (status === google.maps.DirectionsStatus.OK) {
  247.             directionsDisplay.setDirections(response);
  248.           } else {
  249.             console.log('Directions request failed due to ' + status);
  250.           }
  251.         });
  252.       };
  253.  
  254.     directionsDisplay.setMap(this.map);
  255.     displayRoute();
  256.   }
  257.  
  258.   ngAfterContentInit(): void {
  259.     this.geolocation.getCurrentPosition().then((resp) => {
  260.       this.latitude = resp.coords.latitude;
  261.       this.longitude = resp.coords.longitude;
  262.  
  263.       const map = new google.maps.Map(this.mapElement.nativeElement, {
  264.         center: {lat: -3.9768624, lng: 122.5029718},
  265.         zoom: 15
  266.       });
  267.  
  268.       this.map = map;
  269.  
  270.       let markers, poss, contents, icons
  271.  
  272.       this.http.get(this.api_url + 'getLaporan.php').subscribe(data => {
  273.         let temp = JSON.parse(data['_body']);
  274.         this.markersData = temp['server_response'];
  275.         for (var key in this.markersData) {
  276.           if (this.markersData.hasOwnProperty(key)) {
  277.             // console.log()
  278.             poss = {
  279.               lat: +(this.markersData[key]['latitude']),
  280.               lng: +(this.markersData[key]['longitude'])
  281.             }
  282.  
  283.             icons = {
  284.                 url: "../../assets/icon/trash.png", // url
  285.                 scaledSize: new google.maps.Size(30, 30), // scaled size
  286.                 origin: new google.maps.Point(0,0), // origin
  287.                 anchor: new google.maps.Point(0, 0) // anchor
  288.             };
  289.  
  290.             markers = new google.maps.Marker({
  291.               map: map,
  292.               animation: google.maps.Animation.DROP,
  293.               position: poss,
  294.               icon: "http://maps.google.com/mapfiles/marker" + this.markersData[key]['marker']+ ".png",
  295.             });
  296.  
  297.             contents = "<h5> TPS "+this.markersData[key]['no_tps']+"</h5><p>"+this.markersData[key]['keterangan']+"</p>";
  298.  
  299.             this.addInfoWindow(markers, contents, poss);
  300.           }
  301.         }
  302.  
  303.         // this.setRoutesMap(this.markersData)
  304.       }, err=> {
  305.         console.log(err)
  306.       });
  307.  
  308.  
  309.       let pos = {
  310.         lat: this.latitude,
  311.         lng: this.longitude
  312.       };
  313.  
  314.       let icon = {
  315.           url: "../../assets/icon/person.png", // url
  316.           scaledSize: new google.maps.Size(30, 30), // scaled size
  317.           origin: new google.maps.Point(0,0), // origin
  318.           anchor: new google.maps.Point(0, 0) // anchor
  319.       };
  320.  
  321.       let marker = new google.maps.Marker({
  322.         map: map,
  323.         animation: google.maps.Animation.DROP,
  324.         position: pos,
  325.         icon: icon
  326.       });
  327.  
  328.       pos = {
  329.         lat: this.titikAwal['latitude'],
  330.         lng: this.titikAwal['longitude']
  331.       };
  332.  
  333.       icon = {
  334.           url: "../../assets/icon/person.png", // url
  335.           scaledSize: new google.maps.Size(30, 30), // scaled size
  336.           origin: new google.maps.Point(0,0), // origin
  337.           anchor: new google.maps.Point(0, 0) // anchor
  338.       };
  339.  
  340.       marker = new google.maps.Marker({
  341.         map: map,
  342.         animation: google.maps.Animation.DROP,
  343.         position: pos,
  344.         icon: "http://maps.google.com/mapfiles/markerZ.png",
  345.       });
  346.  
  347.       let content = "<h4>Lokasi Anda!</h4>";
  348.       this.addInfoWindow(marker, content, pos);
  349.       // map.setCenter(pos);
  350.     }).catch((error) => {
  351.       console.log('Error getting location', error);
  352.     });
  353.   }
  354.  
  355.   ngOnInit(): void {
  356.   }
  357.  
  358.   async ambilKordinat(){
  359.     console.log('ambil kordinat...')
  360.     this.searching = await true
  361.     this.geolocation.getCurrentPosition().then(async (resp) => {
  362.       this.latitude = resp.coords.latitude;
  363.       this.longitude = resp.coords.longitude;
  364.  
  365.       // this.map = new google.maps.Map(this.mapElement.nativeElement, {
  366.       //   center: {lat: this.latitude, lng: this.longitude},
  367.       //   zoom: 12
  368.       // });
  369.  
  370.       const pos = {
  371.         lat: this.latitude,
  372.         lng: this.longitude,
  373.       };
  374.  
  375.       const icon = {
  376.           url: "../../assets/icon/trash.png", // url
  377.           scaledSize: new google.maps.Size(30, 30), // scaled size
  378.           origin: new google.maps.Point(0,0), // origin
  379.           anchor: new google.maps.Point(0, 0) // anchor
  380.       };
  381.  
  382.       let marker = new google.maps.Marker({
  383.         map: this.map,
  384.         animation: google.maps.Animation.DROP,
  385.         position: pos,
  386.         icon: icon
  387.       });
  388.       //
  389.       let content = "<h4>Lokasi Anda!</h4>";
  390.  
  391.       let data = {
  392.         no_tps: this.no_tps,
  393.         latitude: this.latitude,
  394.         longitude: this.longitude,
  395.         keterangan: this.keterangan
  396.       }
  397.  
  398.       await this.createData(data)
  399.  
  400.       this.addInfoWindow(marker, content, pos);
  401.  
  402.       this.searching = await false
  403.     }).catch(async (error) => {
  404.       console.log('Error getting location', error);
  405.     });
  406.  
  407.   }
  408.  
  409.   addInfoWindow(marker, content, position){
  410.     let infoWindow = new google.maps.InfoWindow({
  411.       content: content
  412.     });
  413.  
  414.     google.maps.event.addListener(marker, 'click', () => {
  415.       infoWindow.open(this.map, marker);
  416.       console.log(position)
  417.     });
  418.   }
  419.  
  420.   createData(data){
  421.     let url = this.api_url+'create_tps.php';
  422.  
  423.     this.http.post(url, JSON.stringify(data)).subscribe(res => {
  424.       try{
  425.         var checkObj = JSON.parse(res['_body']);
  426.         console.log(checkObj)
  427.  
  428.         if(checkObj.message=="sukses"){
  429.           this.loadToast('Laporan Berhasil Dikirim', 1500);
  430.           this.keterangan = '';
  431.         }
  432.  
  433.       }catch(e){
  434.         this.loadToast('Laporan Gagal Dikirim '+e, 2000)
  435.         console.log(e)
  436.       }
  437.     }, err => {
  438.       console.log("Error : "+err)
  439.       this.loadToast('Something Error: '+err, 2000)
  440.     });
  441.  
  442.   }
  443.  
  444.   loadToast(text, duration){
  445.     let toast = this.toastCtrl.create({
  446.       message: text,
  447.       duration: duration
  448.     });
  449.     toast.present();
  450.   }
  451.  
  452.   doRefresh() {
  453.     console.log('Begin async operation');
  454.  
  455.     setTimeout(() => {
  456.       console.log('Async operation has ended');
  457.       this.navCtrl.setRoot(this.navCtrl.getActive().component);
  458.     }, 2000);
  459.   }
  460. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement