Newer
Older
googleMap / src / app / services / googlemap.service.ts
Luis Olaya on 15 Jun 2020 1 KB Direccion
import { Injectable } from "@angular/core";
import { Geolocation } from "@ionic-native/geolocation/ngx";
import { HttpClient } from "@angular/common/http";
import { AlertController } from "@ionic/angular";

@Injectable({
  providedIn: "root",
})
export class GooglemapService {
  public data: any = {};
  TU_LLAVE = "AIzaSyAw_VEeJAY7R9kuABvgz9e9CiKogTW3MFc"; //wtredata
  //TU_LLAVE = "AIzaSyBrY7wrURAlHMM_h__9cCRodYALQg1kuzI"; //mauricio

  constructor(
    private geolocation: Geolocation,
    private http: HttpClient,
    private alertController: AlertController
  ) {}

  

  async loadMap() {
      const myLatLng: any = await this.getLocation();
      this.data.latitud = myLatLng.lat;
      this.data.longitud = myLatLng.lng;

      let data = await this.direccion();
      return data;
  }

  private async getLocation() {
    const rta = await this.geolocation.getCurrentPosition();
    return {
      lat: rta.coords.latitude,
      lng: rta.coords.longitude,
    };
  }

  private async verificationLocation() {}

  /// Permite obtener la direccion y el barrio a partir de las coordenadas
  private direccion() {
    return new Promise((resolve, reject) => {
      const lat = this.data.latitud;
      const long = this.data.longitud;
      this.http
        .get<{ status: string; results: any[] }>(
          `https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${long}&key=${this.TU_LLAVE}`,
          { responseType: "json" }
        )
        .subscribe((e) => {
          if (e.status === "OK") {
            //this.data.direccion = e.results[0].formatted_address;

            //this.data.barrio = e.results[0].address_components[2].long_name;
            resolve({
              dir: e.results[0].formatted_address,
              lat: lat,
              lng: long,
            });
          } else {
            resolve({
              dir: "",
              lat: null,
              lng: null,
            })
          }
        });
    });
  }
}