Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import {Component, Input, OnInit} from '@angular/core';
- import {ElementRef, NgZone, ViewChild} from '@angular/core';
- import {FormControl} from '@angular/forms';
- import {} from 'googlemaps';
- import {MapsAPILoader} from '@agm/core';
- import {CoreService} from './services/core.service';
- import {Observable} from 'rxjs/Observable';
- import {debounceTime, switch, fromEvent}'rxjs/operators';
- @Component({
- selector: 'app-search',
- templateUrl: './search.component.html',
- styleUrls: ['./search.component.scss']
- })
- export class SearchComponent implements OnInit {
- public latitude: number;
- public longitude: number;
- public searchControl: FormControl;
- @ViewChild('search') public searchElementRef: ElementRef;
- public constructor(
- private _core: CoreService,
- private _el: ElementRef,
- private mapsAPILoader: MapsAPILoader,
- private _ngZone: NgZone,
- ) {}
- public ngOnInit(): void {
- // some default hardcoded values
- this.latitude = 39.8282;
- this.longitude = -98.5795;
- this.searchControl = new FormControl();
- // example of connecting google autocomplete to input with promises
- this.mapsAPILoader.load().then(() => {
- const autocomplete: google.maps.places.Autocomplete = new google.maps.places.Autocomplete(
- this.searchElementRef.nativeElement, {
- componentRestrictions: {country: 'ch'},
- types: ['address']
- });
- autocomplete.addListener('place_changed', () => {
- this._ngZone.run(() => {
- const place: google.maps.places.PlaceResult = autocomplete.getPlace();
- this._core.savePlace(place);
- if (place.geometry === undefined || place.geometry === null) {
- return;
- }
- this.latitude = place.geometry.location.lat();
- this.longitude = place.geometry.location.lng();
- });
- });
- });
- // example of RxJS usage with some kind of an instant search
- Observable.fromEvent(this._el.nativeElement, 'keyup')
- .pipe(
- .map((e: any) => e.target.value),
- .filter((text: string) => text.length > 1),
- .debounceTime(250),
- .map(() => this._core.getZip(this.latitude, this.longitude)),
- .switch()
- )
- .subscribe(
- (zip: Zip) => {
- this._core.saveZip(zip);
- },
- (err: Error) => {
- this._core.handleError(err);
- }
- );
- }
- }
Add Comment
Please, Sign In to add comment