1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

TypeError start leafleat

Discussão em 'Angular' iniciado por David Correia, Outubro 9, 2024 às 10:22.

  1. I'm developing an angular app and I have a map using leaflet. Locally it works but when I upload it to render.com it displays the following error below:

    main-2KC2FGCV.js:119 Erro ao carregar o Leaflet: TypeError: this.leaflet.map is not a function
    at t.initializeMap (main-2KC2FGCV.js:119:669)
    at main-2KC2FGCV.js:119:491
    at f.invoke (polyfills-SCHOHYNV.js:1:6450)
    at Object.onInvoke (main-2KC2FGCV.js:7:29726)
    at f.invoke (polyfills-SCHOHYNV.js:1:6390)
    at Y.run (polyfills-SCHOHYNV.js:1:1715)
    at polyfills-SCHOHYNV.js:2:553
    at f.invokeTask (polyfills-SCHOHYNV.js:1:7075)
    at Object.onInvokeTask (main-2KC2FGCV.js:7:29542)
    at f.invokeTask (polyfills-SCHOHYNV.js:1:6996)


    Below is the app.component.ts where I start the map:

    import { Component, OnInit, Inject, PLATFORM_ID } from '@angular/core';
    import { isPlatformBrowser } from '@angular/common';
    import { PinService } from './services/pin/pin.service'; // Certifique-se de ajustar o caminho
    import { Pin } from './models/pin/pin.model';
    import * as L from 'leaflet';

    @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'] // Correção de 'styleUrl' para 'styleUrls'
    })
    export class AppComponent implements OnInit {
    title = 'map';
    items: any[] = [
    { label: 'Home', icon: 'pi pi-home', routerLink: '/' },
    // { label: 'Potencial IG', icon: 'pi pi-map-marker', routerLink: '/pin' },
    ];

    private leaflet: typeof L | null = null; // Adiciona a tipagem correta
    pins: Pin[] = [];
    selectedPin: Pin | null = null;

    constructor(
    @Inject(PLATFORM_ID) private platformId: any,
    private pinService: PinService
    ) {}

    ngOnInit(): void {
    if (isPlatformBrowser(this.platformId)) {
    import('leaflet').then(L => {
    this.leaflet = L;
    this.initializeMap();
    }).catch(err => console.error('Erro ao carregar o Leaflet:', err));
    }
    }

    initializeMap(): void {
    if (!this.leaflet) {
    console.error('Leaflet não carregado.');
    return;
    }

    const map = this.leaflet.map('map').setView([-20.3222, -39.3700], 7);

    this.leaflet.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '© OpenStreetMap contributors'
    }).addTo(map);

    this.pinService.getPins().subscribe({
    next: (pins: Pin[]) => {
    this.pins = pins;
    this.renderPinsOnMap(map);
    },
    error: (err) => console.error('Erro ao obter os pins:', err)
    });
    }

    renderPinsOnMap(map: L.Map): void {
    this.pins.forEach(pin => {
    console.log('Tentando adicionar pin:', pin);

    // Verifica se latitude e longitude são válidos antes de usar
    const latitude = pin.latitude ?? 0; // Usar 0 se for null/undefined
    const longitude = pin.longitude ?? 0; // Usar 0 se for null/undefined

    if (this.isValidCoordinates(latitude, longitude)) {
    const popupContent = this.generatePopupContent(pin);

    const marker = this.leaflet!.marker([latitude, longitude])
    .addTo(map)
    .bindPopup(popupContent);

    marker.on('click', () => {
    this.selectedPin = pin;
    console.log('Pin selecionado:', this.selectedPin);
    });
    } else {
    console.warn('Coordenadas inválidas:', pin);
    }
    });
    }

    isValidCoordinates(latitude: number, longitude: number): boolean {
    return latitude >= -90 && latitude <= 90 && longitude >= -180 && longitude <= 180;
    }

    generatePopupContent(pin: Pin): string {
    // Garantir que os dados sejam do tipo esperado
    const nome = pin.nome || 'Nome não disponível'; // Valor padrão se nome for undefined
    const cidade = pin.cidade || 'Cidade não disponível'; // Valor padrão se cidade for undefined
    const nivelMaturidade = pin.nivelMaturidade ?? 0; // Usar 0 se for null/undefined
    const tipoIndicacao = pin.tipoIndicacao || 'Tipo não disponível'; // Valor padrão se tipoIndicacao for undefined

    return `
    <b>Nome:</b> ${nome}<br>
    <b>Cidade:</b> ${cidade}<br>
    <b>Maturidade:</b> ${this.generateRating(nivelMaturidade)}<br>
    <b>Tipo de Indicação:</b> ${this.formatIndicationType(tipoIndicacao)}
    `;
    }

    generateRating(maturidade: number): string {
    return maturidade > 0 ? '⭐'.repeat(maturidade) : 'N/A';
    }

    formatIndicationType(tipoIndicacao: string): string {
    const tipoMap: { [key: string]: string } = {
    'IDENTIFICACAO_PROCEDENCIA': 'Identificação de Procedência',
    'DENOMINACAO_ORIGEM': 'Denominação de Origem'
    };
    return tipoMap[tipoIndicacao] || tipoIndicacao;
    }
    }


    I'm a bit lost on what to do to get the map to start and load the pins.

    Here's the project URL: https://map-1sn5.onrender.com/

    Local host works

    I have tried to start leaflet in several different ways but none of them work.

    Continue reading...

Compartilhe esta Página