如何等待Google Geocode返回响应?

时间:2019-05-17 12:16:36

标签: angular google-maps angular7

我正在尝试使用带有Google API的地址获取旅行的预计到达时间。 我需要等待地址解析器返回该值。

我尝试使用等待,但它什么也没做。 也尝试过使用defer,但是它说它不存在。

import { Component, OnInit, AfterViewInit, ViewChild } from '@angular/core';
import { OrdersService } from 'src/app/services/orders.service';
import { GoogleMapsAPIWrapper, MapsAPILoader, AgmMap } from '@agm/core';
import {} from 'googlemaps';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-view-order-route',
  templateUrl: './view-order-route.component.html',
  styleUrls: ['./view-order-route.component.css']
})
export class ViewOrderRouteComponent implements OnInit, AfterViewInit {
  list: any[];
  id: string;

  gps: number[];
  start: string;
  goal: string;

  private directionsRenderer: any;
  origin: google.maps.LatLng;
  destination: google.maps.LatLng;
  @ViewChild(AgmMap) agmMap;


  constructor(private ordersService: OrdersService,
              private gmapsApi: GoogleMapsAPIWrapper) { }

  ngOnInit() {
    this.ordersService.getList().subscribe( data => {
      if (data){
        this.list = data;
        console.log("data is: ", data);
      }
    });
    this.id = this.ordersService.getCurrentId();
    let tmpOrder = this.list.find(obj => obj['order_id'].toString() === this.id);

    this.gps = tmpOrder['gps'];
    this.start = tmpOrder['start'];
    this.goal = tmpOrder['goal'];

  }

  ngAfterViewInit(){
    this.eta();
  }

  async eta(){
    console.log("entered eta2 function");
    console.log(this.gmapsApi.getNativeMap());
    this.agmMap.mapReady.subscribe( async map => {
      if (!this.directionsRenderer) {
        console.log("Creating new direction renderer");
        // if you already have a marker at the coordinate location on the map, use suppressMarkers option
        // suppressMarkers prevents google maps from automatically adding a marker for you
        this.directionsRenderer = new google.maps.DirectionsRenderer({suppressMarkers: true});
      }
      const directionsRenderer = this.directionsRenderer;
      console.log("direction renderer assigned");
      let geocoder = new google.maps.Geocoder();
      await this.getLatLng(this.start, this.origin);
      await this.origin;
      console.log("Origin: ", this.origin);
      if ( this.goal ) {
        console.log("starting point: ", this.start, "\n ending point: ", this.goal);
        const directionsService = new google.maps.DirectionsService;
        directionsRenderer.setMap(map);
        directionsService.route(
          {
            origin: {lat: this.origin.lat(), lng: this.origin.lng()},
            destination: this.destination,
            waypoints: [],
            optimizeWaypoints: true,
            travelMode: google.maps.TravelMode.DRIVING
          }, 
          (response, status) => {
            console.log(response);
            if (status === google.maps.DirectionsStatus.OK) {
                directionsRenderer.setDirections(response);
               } 
            else {
                console.log('Directions request failed due to ' + status);
            }
          }
        );
      }
    });
    console.log("eta2 end");

  }

  async getLatLng(address: string, target: any): Promise<any>{
    let geocoder = new google.maps.Geocoder();
    return new Promise(resolve => {
      geocoder.geocode(
        {
          'address': address
        }, 
        (results, status) => {
          if (status == google.maps.GeocoderStatus.OK) {
              console.log(results);
              console.log(typeof(results[0].geometry.location.lat()));
              target = new google.maps.LatLng({
                lat: results[0].geometry.location.lat(),
                lng: results[0].geometry.location.lng()
              });
          } 
          else {
              console.log('Error: ', results, ' & Status: ', status);
          }
      });
      resolve();
    });
  }

}

这是我得到的错误: 未捕获(承诺):TypeError:无法读取未定义的属性“ lat” 发生此错误的原因是this.origin仍未定义。

1 个答案:

答案 0 :(得分:0)

在提供的示例中,已解决的承诺不会返回什么,因为它有望返回LatLng的值,这里是经过修改的版本:

getLatLng(address: string): Promise<google.maps.LatLng> {
    const geocoder = new google.maps.Geocoder();
    return new Promise((resolve, reject) => {
      geocoder.geocode(
        {
          address: address
        },
        (results, status) => {
          if (status === google.maps.GeocoderStatus.OK) {
            const latLng = new google.maps.LatLng({
              lat: results[0].geometry.location.lat(),
              lng: results[1].geometry.location.lng()
            });

            resolve(latLng);
          } else {
            reject(new Error(status));
          }
        }
      );
    });
  }

示例

下面的示例演示如何将Geocoder APIangular-google-maps library结合使用:

export class AppComponent implements OnInit {
  constructor() {}

  protected center = {
    lat: 31.155564,
    lng: -75.524654
  };
  protected zoom = 3;

  @ViewChild(AgmMap) agmMap;

  ngOnInit() {
    this.agmMap.mapReady.subscribe(map => {
      this.geocode("Sydney, NSW").then(place => {
        console.log(place.geometry.location);
      })
      .catch(err => {
        console.log(err);
      });
    });
  }

  geocode(address: string): Promise<any> {
    const geocoder = new google.maps.Geocoder();
    return new Promise((resolve, reject) => {
      geocoder.geocode(
        {
          address: address
        },
        (results, status) => {
          if (status === google.maps.GeocoderStatus.OK) {
            resolve(results[0]);
          } else {
            reject(new Error(status));
          }
        }
      );
    });
  }
}