1 of 43

Profundizando en Angular, Firebase y Google Maps para aplicación en tiempo Real

Sebastian Gomez�Technical Manager, Globant

@sebasgojs

2 of 43

Agenda

2

  1. ¿Cómo funciona on realtime de Uber y Rappi?
  2. Empezando con Google Maps en Angular 9
  3. ¿Qué son los ViewChilds?
  4. Asyn, defer; ngOnInit y posibles errores con los map
  5. ¿Cómo crear tu primer mapa en Angular?
  6. Personalizar los estilos de tu mapa en Angular
  7. ¿Cómo encontrarte en Angular?
  8. ¿Cómo crear y borrar marcadores?
  9. ¿Cómo implementamos el “OnRealTime”?
  10. Usando Firebase

@sebasgojs

3 of 43

1. ¿Como funciona On-Realtime de Uber?

3

@sebasgojs

4 of 43

1. ¿Como funciona On-Realtime de Uber?

4

refreshTime<3s

positionChange> 10mts

notificarUsuario()

Si posición cambió

actualizarMapa()

guardarUltimaPosicion()

@sebasgojs

5 of 43

1. ¿Como funciona On-Realtime de Uber?

5

refreshTime<3s

Si posición Cambió actualizarMapa()

lat: -34.536294,

lng: -58.466651

Estoy Aquí

lat: -34.536294,

lng: -58.466651

El mansito dijo que estaba ahí

notificarUsuario()

@sebasgojs

6 of 43

async function gpsTracking() {

const coords = await getCurrentPosition();

await sendToServer(coords)

// optional delay;

gpsTracking();

}

6

@sebasgojs

7 of 43

¿Qué opciones tenemos?

7

Angular Maps

Google Maps Javascript API

@angular/google-maps

@sebasgojs

8 of 43

2. Empezando con Google Maps en Angular

<script

async defer

src="https://maps.googleapis.com/maps/api/js?

key=<TuSuperKeySeguraYSecreta>"

type="text/javascript"

>

</script>

8

@sebasgojs

9 of 43

2. Empezando con Google Maps en Angular

<script

async defer

src="https://maps.googleapis.com/maps/api/js?

key=<TuSuperKeySeguraYSecreta>"

type="text/javascript"

>

</script>

9

@sebasgojs

10 of 43

10

@sebasgojs

11 of 43

Asyn, defer; ngOnInit y posibles errores con los Mapas

11

Async

Defer

ngOnInit, ngAfterInit,

...

Browser Threat

sync

Browser Threat

ngOnInit, ngAfterInit,

...

@sebasgojs

12 of 43

¿Qué son los ViewChilds?

@ViewChild("map", {static: true}) mapElement: ElementRef;

12

<h1>...</h1>

<div #map id="map"></div>

<otro-componente></otro-componente>

@sebasgojs

13 of 43

¿Qué son los ViewChilds?

@ViewChild("map", {

read: false, static: true

}) mapElement: ElementRef;

13

<h1>...</h1>

<div #map id="map"></div>

<otro-componente></otro-componente>

@sebasgojs

14 of 43

Entendiendo el concepto de ViewChild - Child

14

export class FilterComponent {

@Output() changed: EventEmitter<string>;

filter: string;

clear() {

this.filter = '';

}

// ... other methods

}

Child Component (Componente Hijo)

Método que nos interesa

@sebasgojs

15 of 43

Entendiendo el concepto de ViewChild - Parent

15

export class CharterListComponent {

characters: Character[];

@ViewChild(FilterComponent, {}) filter: FilterComponent;

filtered = this.characters;

getCharacters() {

this._charactersService.getCharacters().subscribe(characters => {

this.characters = this.filtered = characters;

this.filter.clear();

});

}

}

Obtenemos el componente

Método del componente hijo que podemos ejecutar

@sebasgojs

16 of 43

¿Cómo crear tu primer mapa en Angular?

16

let latLng = new google.maps.LatLng(6.236654, -75.580432);

let mapOptions = {

center: latLng,

zoom: 13,

mapTypeId: google.maps.MapTypeId.ROADMAP

};

this.map = new google.maps.Map(

this.mapElement.nativeElement, mapOptions);

@sebasgojs

17 of 43

Para personalizar los estilos del mapa

17

let latLng = new google.maps.LatLng(6.236654, -75.580432);

let mapOptions = {

center: latLng,

zoom: 13,

mapTypeId: google.maps.MapTypeId.ROADMAP,

styles: [...],

};

this.map = new google.maps.Map(

this.mapElement.nativeElement, mapOptions);

Array para personalizar los estilos del mapa

@sebasgojs

18 of 43

Proveedores de estilos para Google Maps

18

@sebasgojs

19 of 43

¿Cómo localizarte en el navegador?

19

window.

navigator.

geolocation.

getCurrentPosition(funcionQueLlamoEnCasoDeExito,

functionQueLlamoEnCasoDeFracaso)

@sebasgojs

20 of 43

¿Como encontrarte en Angular?

20

funcionQueLlamoEnCasoDeExito(position)

{...

coords: {

latitude: 6.208488,

longitude: -75.563577

}

...

}

@sebasgojs

21 of 43

¿Como crear y borrar marcadores?

21

let latLng = new google.maps.LatLng(

position.coords.latitude,

position.coords.longitude

);

this.myMarker = new google.maps.Marker({

map: this.map,

animation: google.maps.Animation.cn,

position: latLng,

icon: { url: "assets/photo.jpg" }

});

this.myMarker.setMap(null);

this.myMarker = null;

@sebasgojs

22 of 43

¿Y el tiempo Real?

22

@sebasgojs

23 of 43

23

@sebasgojs

24 of 43

24

Desarrollo

@sebasgojs

25 of 43

25

Crecimiento

@sebasgojs

26 of 43

26

@sebasgojs

27 of 43

27

Optimizada para el uso sin conexión

@sebasgojs

28 of 43

28

Optimizada para el uso sin conexión

Firestore

  • Documentos y Colecciones con mejores peticiones.
  • SDKs robustos con acceso Offline.
  • Realtime sincronización.
  • Replicación multi regional automática.�

Modelo de Datos

@sebasgojs

29 of 43

29

Documento

Colecciones�

@sebasgojs

30 of 43

30

Firebase Database VS Firestore

@sebasgojs

31 of 43

31

Consultas en Firebase Database

@sebasgojs

32 of 43

32

@sebasgojs

33 of 43

33

this.positions = this.positionsCollection

.doc("PUhz5BIUIBMQNayHDWwD")

.valueChanges();

this.positions.subscribe(position => {

this.pintarUnMarcador(position);

}

this.positionsCollection = this.afs.collection("positions",

ref => ref.orderBy("order")

);

1

2

@sebasgojs

34 of 43

Ahora usando Angular-maps

34

@sebasgojs

35 of 43

Implementando angular-maps

35

npm install @agm/core --save

@sebasgojs

36 of 43

Implementando angular-maps

36

import { AgmCoreModule } from "@agm/core";

@NgModule({

declarations: [AppComponent],

imports: [

...

AgmCoreModule.forRoot({

apiKey: "..."

})

],

@sebasgojs

37 of 43

Implementando angular-maps

37

<agm-map [latitude]="lat" [longitude]="lng" [zoom]="13">

<agm-marker [latitude]="mylat" [longitude]="mylng" iconUrl="assets/photo.jpg">

<agm-info-window>

<strong>My Location</strong>

</agm-info-window>

</agm-marker>

</agm-map>

@sebasgojs

38 of 43

Implementando marcadores en angular-maps

38

<agm-marker

*ngIf="tracking" [latitude]="hislat"

[longitude]="hislng" iconUrl="assets/moto.png"

>

<agm-info-window>

<strong>Food Location</strong>

</agm-info-window>

</agm-marker>

@sebasgojs

39 of 43

Ruta usando una polyline angular-maps

39

<agm-map

[latitude]="currentCenter.lat"

[longitude]="currentCenter.lng"

[zoom]="defaultZoom"

*ngIf="currentCenter"

>

<agm-polyline [strokeColor]="'red'" *ngIf="coordinates">

<agm-polyline-point

*ngFor="let coords of coordinates"

[latitude]="coords.lat"

[longitude]="coords.lng"

>

</agm-polyline-point>

</agm-polyline>

</agm-map>

@sebasgojs

40 of 43

40

@sebasgojs

41 of 43

41

Dales una estrella!

@sebasgojs

42 of 43

Conclusiones

  • La implementación de Google Maps Javascript Api en Angular te da más control de tu código.
  • Con Google Maps Javascript la lógica de tu mapa se programa en el controlador componente.
  • La implementación con AGM reduce significativamente las líneas de código a escribir.
  • Con AGM la lógica del mapa se programa en la vista del componente.
  • Con AGM no hubieras aprendido ViewChild.
  • Performance con AGM es mejor porque reduce ciclos de implementación de marcadores.

42

@sebasgojs

43 of 43

www.sebastian-gomez.com

43

Sebastian Gomez�Technical Manager, Globant

@sebasgojs

@sebasgojs