Skip to content

Instantly share code, notes, and snippets.

@alextoul
Created July 2, 2016 17:42
Show Gist options
  • Save alextoul/1a922bd5189205db2672e0482e0b18df to your computer and use it in GitHub Desktop.
Save alextoul/1a922bd5189205db2672e0482e0b18df to your computer and use it in GitHub Desktop.
Expansion app
import { Component } from '@angular/core';
import {
GOOGLE_MAPS_DIRECTIVES,
GOOGLE_MAPS_PROVIDERS
} from 'angular2-google-maps/core';
import {AngularFire} from 'angularfire2';
import { Http, Response, URLSearchParams } from '@angular/http';
import {Observable} from 'rxjs/Rx';
import {lessThan} from './less-than.pipe'
@Component({
moduleId: module.id,
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css'],
directives: [GOOGLE_MAPS_DIRECTIVES],
pipes: [lessThan]
})
export class AppComponent {
title = 'app works great!';
lng: number = -73.6544332;
lat: number = 45.5338225;
zoom: number = 10;
trips: any;
response: any;
origin: {text: string, lng?: number, lat?: number};
destination: {text?: string, lng?: number, lat?: number};
counter: number = 0;
maxDurationTime: number = 20;
constructor(
private firebase: AngularFire,
private http: Http
) {
console.log('Initialize');
let that = this;
this.trips = this.firebase.database.list('/trips');
this.calculateDistance()
}
calculateDistance() {
console.log('calculateDistance')
let that = this;
this.origin = {text: "Rue du Marché Central, Montreal, Québec H4N 3J5, Canada"};
this.getLatLngFromAddress(this.origin.text).subscribe(location => {
this.origin.lat = location.lat;
this.origin.lng = location.lng;
this.getAnAddressKmAwayFromOrigin(40)
.subscribe(res => {});
})
if (this.counter < 1000) {
this.counter += 1;
// setTimeout(function(){
// that.calculateDistance()
// },200)
}
}
calculateDistanceInTraffic(origin: any, destination: any) {
let that = this;
let departure_time = Date.now();
this.googleAPICall('distancematrix',{
origins: origin,
destinations: destination,
traffic_mode: 'best_guess',
departure_time: departure_time.toString()
}).map(response => {
let result = response.json();
result.departure_time = departure_time;
that.storeResult(result);
return result;
})
.subscribe(res => this.response = res);
}
getAnAddressKmAwayFromOrigin(km : number) {
let that = this;
let d = 0.0090; // Degree per km
that.destination = {};
let items = [1,-1];
let delta_lat = (d * km * Math.random()) * items[Math.floor(Math.random()*items.length)]
let delta_lng = (d * km * Math.random()) * items[Math.floor(Math.random()*items.length)]
that.destination.lat = this.origin.lat + delta_lat;
that.destination.lng = this.origin.lng + delta_lng;
let distance = this.calculateDistanceBetweenLatLong(that.origin,that.destination);
console.log('Distance',distance);
return this.googleAPICall('geocode',{'latlng': that.destination.lat+","+that.destination.lng})
.map(response => {
let result = response.json();
that.destination = {
text: response.json().results[0].formatted_address,
lat: response.json().results[0].geometry.location.lat,
lng: response.json().results[0].geometry.location.lng,
};
that.calculateDistanceInTraffic(that.origin.text,that.destination.text)
return result;
})
}
calculateDistanceBetweenLatLong(origin, destination) {
var unit = "K";
var radlat1 = Math.PI * origin.lat/180
var radlat2 = Math.PI * destination.lat/180
var theta = origin.lng-destination.lng
var radtheta = Math.PI * theta/180
var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
dist = Math.acos(dist)
dist = dist * 180/Math.PI
dist = dist * 60 * 1.1515
if (unit=="K") { dist = dist * 1.609344 }
if (unit=="N") { dist = dist * 0.8684 }
return dist
}
private getLatLngFromAddress(address: string) {
return this.googleAPICall('geocode',{'address':address}).map(res => {
let location = res.json().results[0].geometry.location;
return location;
})
}
private googleAPICall(url: string, params: any) {
let p: URLSearchParams = new URLSearchParams();
for (var key in params) {
p.set(key, params[key]);
}
return this.http
.get("https://maps.googleapis.com/maps/api/"+url+"/json?key=AIzaSyDOSbqfk6SNsLPkG5_-lUl8mwAg1oFa7pc",{search: p})
}
private storeResult(result: any) {
let trip = {
from: result.origin_addresses[0],
to: result.destination_addresses[0],
duration_value: result.rows[0].elements[0].duration.value,
duration_text: result.rows[0].elements[0].duration.text,
distance_value: result.rows[0].elements[0].distance.value,
distance_text: result.rows[0].elements[0].distance.text,
duration_in_traffic_value: result.rows[0].elements[0].duration_in_traffic.value,
duration_in_traffic_text: result.rows[0].elements[0].duration_in_traffic.text,
from_lat: this.origin.lat,
from_lng: this.origin.lng,
to_lat: this.destination.lat,
to_lng: this.destination.lng,
departure_time: result.departure_time
}
console.log(trip.from + ' to ' + trip.to +' is ' + trip.distance_text + ' away and takes ' + trip.duration_text);
this.firebase.database.list('trips').push(trip);
}
transformTimestampToTime(unix_timestamp) {
// Create a new JavaScript Date object based on the timestamp
// multiplied by 1000 so that the argument is in milliseconds, not seconds.
var date = new Date(unix_timestamp*1000);
// Hours part from the timestamp
var hours = date.getHours();
// Minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// Seconds part from the timestamp
var seconds = "0" + date.getSeconds();
// Will display time in 10:30:23 format
return hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment