Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Component, ViewChild, OnInit, AfterContentInit } from '@angular/core';
- import { NavController, ToastController, LoadingController } from 'ionic-angular';
- import { Geolocation } from '@ionic-native/geolocation';
- declare var google;
- import { Http } from "@angular/http";
- import "rxjs/add/operator/map";
- import 'rxjs/add/operator/toPromise';
- import 'rxjs/Observable';
- @Component({
- selector: 'page-laporan',
- templateUrl: 'laporan.html'
- })
- export class LaporanPage implements OnInit, AfterContentInit{
- // api_url: string = 'https://clean-troops.000webhostapp.com/api/';
- // api_url: string = 'http://localhost/clean_api/';
- dataLaporan: any
- map: any
- @ViewChild('mapElement') mapElement;
- latitude: any
- longitude: any
- no_tps: string
- keterangan: string
- // api_url: string = 'http://localhost/clean_api/';
- api_url: string = 'http://clean-troops.000webhostapp.com/api/';
- markersData: any
- searching = false
- titikAwal:any = {
- 'latitude': -3.989146,
- 'longitude': 122.468892,
- 'marker': 'TPA'
- }
- jumlahLebah: number
- allPaths:any = []
- jaraks:any = []
- shortPath = 99999
- constructor(
- public navCtrl: NavController,
- public http: Http,
- public geolocation: Geolocation,
- public toastCtrl: ToastController,
- public loadingCtrl: LoadingController
- ) {
- this.http.get(this.api_url + 'getLaporan.php').subscribe(async data => {
- let temp = await JSON.parse(data['_body']);
- this.dataLaporan = await temp['server_response'];
- console.log(this.dataLaporan)
- }, err=> {
- console.log(err)
- });
- }
- randomNumber(){
- return Math.floor(Math.random() * (this.dataLaporan.length - 1) + 1)
- }
- BCO(){
- this.allPaths = new Array()
- for (let i = 0; i < this.jumlahLebah; i++) {
- const allPoints = [
- {'x':'A', 'y':0},
- {'x':'B', 'y':1},
- {'x':'C', 'y':2},
- {'x':'D', 'y':3},
- {'x':'E', 'y':4},
- {'x':'F', 'y':5},
- {'x':'G', 'y':6},
- {'x':'H', 'y':7},
- {'x':'I', 'y':8},
- {'x':'J', 'y':9},
- {'x':'K', 'y':10},
- {'x':'L', 'y':11},
- {'x':'M', 'y':12},
- {'x':'N', 'y':13},
- {'x':'O', 'y':14},
- {'x':'P', 'y':15}
- ];
- for (let i = 0; i < allPoints.length; i++) {
- if(allPoints[i]['x']==this.titikAwal['marker']){
- allPoints.splice(i,1)
- }
- }
- this.titikAwalFunc(allPoints);
- }
- console.log(this.allPaths)
- }
- async titikAwalFunc(points){
- this.http.get(this.api_url + 'getLaporan.php').subscribe(data => {
- let temp = JSON.parse(data['_body']);
- this.markersData = temp['server_response'];
- console.log(points)
- let newPath = new Array()
- let pl = points.length
- for (let i = 0; i < pl; i++) {
- let rand = Math.floor(Math.random() * (points.length))
- // newPath.push(points[rand])
- for(let key in this.markersData) {
- // if(this.markersData[key]['marker']==this.titikAwal['marker']){
- // this.markersData.splice(key, 1)
- // }
- if(this.markersData[key]['marker']==points[rand]['x']){
- newPath.push(this.markersData[key]['marker'])
- // console.log(this.markersData[key]['marker'])
- }
- }
- let cut = points.splice(rand, 1)
- }
- this.setRoutesMap(newPath, this.allPaths.length)
- this.allPaths.push(newPath)
- }, err=> {
- console.log(err)
- });
- }
- haversineDistance(lon1, lat1, lon2, lat2){
- function toRad(x) {
- return x * Math.PI / 180;
- }
- // lon1 = -3.985462;
- // lat1 = 122.496236;
- //
- // lon2 = -3.971944;
- // lat2 = 122.506407;
- var R = 6371; // Earth’s mean radius in meter
- var dLat = toRad(lat2 - lat1);
- var dLong = toRad(lon2 - lon1);
- var a =
- Math.sin(dLat / 2) * Math.sin(dLat / 2) +
- Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) *
- Math.sin(dLong / 2) * Math.sin(dLong / 2);
- var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
- var d = R * c;
- d /= 1.60934;
- d = Math.round(d * 100) / 100
- return d; // returns the distance in km
- }
- reorderObject(data){
- let newMarkerObj = new Array()
- for(let key in this.markersData){
- newMarkerObj[this.markersData[key]['marker']] = this.markersData[key]
- }
- return newMarkerObj
- }
- setRoutesMap(data, i){
- console.log(data)
- let start_lat = this.titikAwal['latitude'];
- let start_lng = this.titikAwal['longitude'];
- let newMarkerObj = this.reorderObject(this.markersData)
- let newRoutesWaypoints = new Array()
- for(let i = 0; i < data.length; i++) {
- newRoutesWaypoints.push(newMarkerObj[data[i]])
- }
- let finish_lat = newRoutesWaypoints[Object.keys(newRoutesWaypoints).length-1]['latitude'];
- let finish_lng = newRoutesWaypoints[Object.keys(newRoutesWaypoints).length-1]['longitude'];
- let waypoints = [];
- let prevMarker = this.titikAwal['marker']
- let prevRouteLat = start_lat
- let prevRouteLng = start_lng
- let jarak
- let totalJarak = 0
- for (var key in newRoutesWaypoints) {
- if (data.hasOwnProperty(key)) {
- waypoints.push({
- location: new google.maps.LatLng(newRoutesWaypoints[key]['latitude'], newRoutesWaypoints[key]['longitude']),
- stopover: true
- });
- //hitung jarak
- jarak = this.haversineDistance(
- prevRouteLat,
- prevRouteLng,
- newRoutesWaypoints[key]['latitude'],
- newRoutesWaypoints[key]['longitude']
- );
- console.log(prevMarker+ " -> "+ newRoutesWaypoints[key]['marker'] +' : '+jarak+' km')
- totalJarak+=jarak;
- prevMarker = newRoutesWaypoints[key]['marker']
- prevRouteLat = newRoutesWaypoints[key]['latitude']
- prevRouteLng = newRoutesWaypoints[key]['longitude']
- }
- }
- jarak = this.haversineDistance(
- prevRouteLat,
- prevRouteLng,
- this.titikAwal['latitude'],
- this.titikAwal['longitude']
- );
- totalJarak+=jarak
- console.log(prevMarker+ " -> "+ this.titikAwal['marker'] +' : '+jarak+' km')
- waypoints.push({
- location: new google.maps.LatLng(this.titikAwal['latitude'], this.titikAwal['longitude']),
- stopover: true
- });
- totalJarak+=Math.round(jarak * 100) / 100;
- let prevPath = this.shortPath
- this.shortPath = totalJarak<=prevPath ? totalJarak : this.shortPath
- this.jaraks[i] = totalJarak
- console.log('Total Jarak : '+totalJarak+' km')
- var directionsService = new google.maps.DirectionsService(),
- directionsDisplay = new google.maps.DirectionsRenderer({
- suppressMarkers: true
- }),
- displayRoute = function() {
- directionsService.route({
- origin: new google.maps.LatLng(start_lat, start_lng), // Pass this in place of the address 'Akin Ogunlewe street VI'
- destination: new google.maps.LatLng(finish_lat, finish_lng), // Pass this in place of the address 'Falolu road Surulere'
- waypoints: waypoints,
- travelMode: google.maps.TravelMode.DRIVING
- }, function(response, status) {
- if (status === google.maps.DirectionsStatus.OK) {
- directionsDisplay.setDirections(response);
- } else {
- console.log('Directions request failed due to ' + status);
- }
- });
- };
- directionsDisplay.setMap(this.map);
- displayRoute();
- }
- ngAfterContentInit(): void {
- this.geolocation.getCurrentPosition().then((resp) => {
- this.latitude = resp.coords.latitude;
- this.longitude = resp.coords.longitude;
- const map = new google.maps.Map(this.mapElement.nativeElement, {
- center: {lat: -3.9768624, lng: 122.5029718},
- zoom: 15
- });
- this.map = map;
- let markers, poss, contents, icons
- this.http.get(this.api_url + 'getLaporan.php').subscribe(data => {
- let temp = JSON.parse(data['_body']);
- this.markersData = temp['server_response'];
- for (var key in this.markersData) {
- if (this.markersData.hasOwnProperty(key)) {
- // console.log()
- poss = {
- lat: +(this.markersData[key]['latitude']),
- lng: +(this.markersData[key]['longitude'])
- }
- icons = {
- url: "../../assets/icon/trash.png", // url
- scaledSize: new google.maps.Size(30, 30), // scaled size
- origin: new google.maps.Point(0,0), // origin
- anchor: new google.maps.Point(0, 0) // anchor
- };
- markers = new google.maps.Marker({
- map: map,
- animation: google.maps.Animation.DROP,
- position: poss,
- icon: "http://maps.google.com/mapfiles/marker" + this.markersData[key]['marker']+ ".png",
- });
- contents = "<h5> TPS "+this.markersData[key]['no_tps']+"</h5><p>"+this.markersData[key]['keterangan']+"</p>";
- this.addInfoWindow(markers, contents, poss);
- }
- }
- // this.setRoutesMap(this.markersData)
- }, err=> {
- console.log(err)
- });
- let pos = {
- lat: this.latitude,
- lng: this.longitude
- };
- let icon = {
- url: "../../assets/icon/person.png", // url
- scaledSize: new google.maps.Size(30, 30), // scaled size
- origin: new google.maps.Point(0,0), // origin
- anchor: new google.maps.Point(0, 0) // anchor
- };
- let marker = new google.maps.Marker({
- map: map,
- animation: google.maps.Animation.DROP,
- position: pos,
- icon: icon
- });
- pos = {
- lat: this.titikAwal['latitude'],
- lng: this.titikAwal['longitude']
- };
- icon = {
- url: "../../assets/icon/person.png", // url
- scaledSize: new google.maps.Size(30, 30), // scaled size
- origin: new google.maps.Point(0,0), // origin
- anchor: new google.maps.Point(0, 0) // anchor
- };
- marker = new google.maps.Marker({
- map: map,
- animation: google.maps.Animation.DROP,
- position: pos,
- icon: "http://maps.google.com/mapfiles/markerZ.png",
- });
- let content = "<h4>Lokasi Anda!</h4>";
- this.addInfoWindow(marker, content, pos);
- // map.setCenter(pos);
- }).catch((error) => {
- console.log('Error getting location', error);
- });
- }
- ngOnInit(): void {
- }
- async ambilKordinat(){
- console.log('ambil kordinat...')
- this.searching = await true
- this.geolocation.getCurrentPosition().then(async (resp) => {
- this.latitude = resp.coords.latitude;
- this.longitude = resp.coords.longitude;
- // this.map = new google.maps.Map(this.mapElement.nativeElement, {
- // center: {lat: this.latitude, lng: this.longitude},
- // zoom: 12
- // });
- const pos = {
- lat: this.latitude,
- lng: this.longitude,
- };
- const icon = {
- url: "../../assets/icon/trash.png", // url
- scaledSize: new google.maps.Size(30, 30), // scaled size
- origin: new google.maps.Point(0,0), // origin
- anchor: new google.maps.Point(0, 0) // anchor
- };
- let marker = new google.maps.Marker({
- map: this.map,
- animation: google.maps.Animation.DROP,
- position: pos,
- icon: icon
- });
- //
- let content = "<h4>Lokasi Anda!</h4>";
- let data = {
- no_tps: this.no_tps,
- latitude: this.latitude,
- longitude: this.longitude,
- keterangan: this.keterangan
- }
- await this.createData(data)
- this.addInfoWindow(marker, content, pos);
- this.searching = await false
- }).catch(async (error) => {
- console.log('Error getting location', error);
- });
- }
- addInfoWindow(marker, content, position){
- let infoWindow = new google.maps.InfoWindow({
- content: content
- });
- google.maps.event.addListener(marker, 'click', () => {
- infoWindow.open(this.map, marker);
- console.log(position)
- });
- }
- createData(data){
- let url = this.api_url+'create_tps.php';
- this.http.post(url, JSON.stringify(data)).subscribe(res => {
- try{
- var checkObj = JSON.parse(res['_body']);
- console.log(checkObj)
- if(checkObj.message=="sukses"){
- this.loadToast('Laporan Berhasil Dikirim', 1500);
- this.keterangan = '';
- }
- }catch(e){
- this.loadToast('Laporan Gagal Dikirim '+e, 2000)
- console.log(e)
- }
- }, err => {
- console.log("Error : "+err)
- this.loadToast('Something Error: '+err, 2000)
- });
- }
- loadToast(text, duration){
- let toast = this.toastCtrl.create({
- message: text,
- duration: duration
- });
- toast.present();
- }
- doRefresh() {
- console.log('Begin async operation');
- setTimeout(() => {
- console.log('Async operation has ended');
- this.navCtrl.setRoot(this.navCtrl.getActive().component);
- }, 2000);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement