Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // utils/config.ts
- export const WEATHER_API_KEY = 'xxxx'; // get from http://openweathermap.org/
- export const WEATHER_API_URL = 'https://api.openweathermap.org/data/2.5/weather?q=';
- export const GMAP_API_URL = 'https://maps.googleapis.com/maps/api/staticmap?center=';
- export const GMAP_API_KEY = 'xxxx'; // get from https://developers.google.com/maps/documentation/javascript/overview
- // app.component.ts
- import { Component, OnInit } from "@angular/core";
- import { FormControl } from "@angular/forms";
- import { HttpClient } from "@angular/common/http";
- import {
- catchError,
- debounceTime,
- distinctUntilChanged,
- filter,
- map,
- startWith,
- switchMap
- } from "rxjs/operators";
- import { of } from "rxjs";
- import { Meteo, ShortMeteo } from "./model/meteo";
- import {
- WEATHER_API_URL,
- WEATHER_API_KEY,
- GMAP_API_URL,
- GMAP_API_KEY
- } from "./utils/config";
- @Component({
- selector: "my-app",
- template: `
- <div class="card">
- <!--Search city input -->
- <input type="text" placeholder="Search City" />
- <!--Temp + icon-->
- <div class="title-bar">
- 30° <img src="http://openweathermap.org/img/w/01n.png" alt="icon" />
- </div>
- <!--Map-->
- <img
- src="https://maps.googleapis.com/maps/api/staticmap?center=Italy&zoom=5&size=200x100&key=AIzaSyDSBmiSWV4-AfzaTPNSJhu-awtfBNi9o2k"
- width="100%"
- alt="map"
- />
- </div>
- `,
- styles: [``]
- })
- export class AppComponent implements OnInit {
- cityInput: FormControl = new FormControl();
- meteo: ShortMeteo;
- constructor(private http: HttpClient) {}
- ngOnInit(): void {
- this.cityInput.valueChanges
- .pipe(
- debounceTime(1000),
- filter(city => city.length >= 3),
- distinctUntilChanged(),
- switchMap(city =>
- this.http
- .get<Meteo>(
- WEATHER_API_URL + city + "&units=metric&APPID=" + WEATHER_API_KEY
- )
- .pipe(
- map((result: Meteo) => ({
- temp: result.main.temp,
- icon: `http://openweathermap.org/img/w/${
- result.weather[0].icon
- }.png`,
- gmap: `${GMAP_API_URL}Italy&zoom=5&size=200x100&key=${GMAP_API_KEY}`,
- error: false
- })),
- catchError(() => of({ error: true }))
- )
- )
- )
- .subscribe(obj => (this.meteo = obj));
- this.cityInput.setValue("Milan");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement