maps.component.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import { Component, OnInit, NgZone } from '@angular/core';
  2. import { latLng, tileLayer, marker, Layer, icon, Map, latLngBounds, LatLng, LatLngBounds, point } from 'leaflet';
  3. import { Plant } from 'src/app/models/plant';
  4. import { PlantsService } from 'src/app/services/plants.service';
  5. @Component({
  6. selector: 'app-maps',
  7. templateUrl: './maps.component.html',
  8. styleUrls: ['./maps.component.scss']
  9. })
  10. export class MapsComponent implements OnInit {
  11. listData: any;
  12. markers: Layer[] = [];
  13. points: LatLng[] = [];
  14. plantId: number;
  15. icon = icon({
  16. iconSize: [25, 41],
  17. iconAnchor: [13, 41],
  18. iconUrl: 'assets/img/marker-icon.png',
  19. //shadowUrl: 'marker-shadow.png'
  20. });
  21. constructor(private plantsService: PlantsService, private zone: NgZone) {
  22. }
  23. // Open Street Map definitions
  24. LAYER_OSM = tileLayer(
  25. 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
  26. {
  27. maxZoom: 18,
  28. attribution: '© OpenStreetMap contributors'
  29. });
  30. // Values to bind to Leaflet Directive
  31. options = {
  32. layers: [this.LAYER_OSM],
  33. zoom: 8,
  34. center: latLng([13.661714, -89.251530])
  35. };
  36. ngOnInit() {
  37. this.plantsService.getAllAssets().subscribe(res => {
  38. this.listData = res;
  39. });
  40. this.addMarkers();
  41. }
  42. addMarkers() {
  43. for (const plant of this.listData) {
  44. const name = plant.name;
  45. const lat = plant.latitud;
  46. const long = plant.longitud;
  47. const newMarker = marker(
  48. [lat, long],
  49. { icon: this.icon })
  50. .bindPopup('<b>' + plant.name + '</b><br>Dirección: ' + plant.address)
  51. .on('click', () => {
  52. this.zone.run(() => {
  53. this.sendPlantId(plant.id);
  54. });
  55. });
  56. this.points.push(latLng([lat, long]));
  57. this.markers.push(newMarker);
  58. }
  59. }
  60. sendPlantId(id: number) {
  61. this.plantId = id;
  62. }
  63. onMapReady(map: Map) {
  64. setTimeout(() => {
  65. map.invalidateSize();
  66. }, 0);
  67. const bounds = latLngBounds(this.points);
  68. map.fitBounds(bounds, {
  69. padding: point(24, 24),
  70. maxZoom: 10.5,
  71. animate: true
  72. });
  73. }
  74. }