0

Sou novo no ionic e angular. Estou buscando os lugares próximos usando nearbySearch() que retorna um resolve do results, deste results pego o place_id do lugar e coloco na função getDetails(), porém quando vou atribuir o resultado da getDetails(place) a uma outra para exporta-la, enfrento esse erro abaixo.

TypeError: this is null[Learn More] js-maps.ts:48:14 init js-maps.ts:48 l3 places_impl.js:19 j3 places_impl.js:17 e

places_impl.js:4 c common.js:67

PlaceService.GetPlaceDetails:1

Segue meu codigo.

import { Injectable } from '@angular/core';
import { Geolocation } from '@ionic-native/geolocation';

declare var google;

@Injectable()
export class JsMapsProvider {
 
  map: any;
  places : Array<any>;
  farmaciasId :Array<any>;
  detalhesfarma: Array<object>;
  servico: any;
  farmacias :Array<any>;

  constructor(public geolocation : Geolocation) { }

  init(location, element){

    let latLng = new google.maps.LatLng(location.latitude, location.longitude);
 
    let opts = {
      center: latLng,
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
 
    this.map = new google.maps.Map(element.nativeElement, opts);
    var service = new google.maps.places.PlacesService(this.map);

    this.getFarmas(latLng).then((place : Array<any>)=>{
      this.places = place;      
      
      for(let i = 0 ;i < place.length ; i++)
      {
        this.createMarker(place[i]);

        service.getDetails({
          placeId:place[i].place_id
          },function (place, status){
            if (status === google.maps.places.PlacesServiceStatus.OK) {
              **this.detalhesfarma = place;**
            }
          } 
        );
      }
    },(status)=>console.log(status));
    
    this.addMarker(this.map);
    
  }

  getFarmas(latLng){

    var service = new google.maps.places.PlacesService(this.map);
    this.servico = service;

    let request = {
        location : latLng,
        //radius : 2000 ,
        types: ['pharmacy'],
        rankBy: google.maps.places.RankBy.DISTANCE
    };
    return new Promise((resolve,reject)=>{
        service.nearbySearch(request,function(results,status){
              if(status === google.maps.places.PlacesServiceStatus.OK)
              {                 
                  resolve(results);
              }else
              {
                  reject(status);
              }

        }); 
    });
  }

  
  createMarker(place){
    
    let marker = new google.maps.Marker({
    map: this.map,
    animation: google.maps.Animation.DROP,
    icon: 'assets/icon/icon-29.png',
    position: place.geometry.location
    });

    
             
    let infoWindow = new google.maps.InfoWindow({});
    
      google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent('<div><strong>' + place.name + '</strong><br>' +
          'Endereço: ' + place.vicinity + '</div>');
        infoWindow.open(this.map, this);
      });


  }

  addMarker(map:any){

    let marker = new google.maps.Marker({
      map: map,
      animation: google.maps.Animation.BOUNCE,
      position: map.getCenter()
    });

    //adicionado 18/01
    let content = "<p>Estou aqui !</p>";          
    let infoWindow = new google.maps.InfoWindow({
    content: content
    });

    google.maps.event.addListener(marker, 'click', () => {
    infoWindow.open(this.map, marker);
    });
    //-----


  }
}
1
  • Seu erro está aqui **this.detalhesfarma = place;**?
    – Marconi
    27/02/2019 às 17:39

1 Resposta 1

0

Deduzindo que seu erro esteja aqui **this.detalhesfarma = place;**. Você tem uma função de retorno de chamada anônima que sobrescreve this, você pode atribuir this a outra variável antes de usá-la em sua função anônima ou usar Arrow Function que faz referência ao escopo pai.

Arrow Function

    service.getDetails({
      placeId:place[i].place_id
      },(place, status) => {
        if (status === google.maps.places.PlacesServiceStatus.OK) {
          **this.detalhesfarma = place;**
        }
      } 
    );

Referência

    var self = this
    service.getDetails({
      placeId:place[i].place_id
      },function(place, status) {
        if (status === google.maps.places.PlacesServiceStatus.OK) {
          self.detalhesfarma = place;
        }
      } 
    );
2
  • Obrigado Marconi !!! 7/03/2019 às 14:59
  • @WelingtonCruz por nada rs, conseguiu compreender o problema?
    – Marconi
    7/03/2019 às 16:54

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .