如何等待谷歌地理编码返回响应? [英] How to wait for google geocode to return a response?

查看:29
本文介绍了如何等待谷歌地理编码返回响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用带有 google API 的地址获取行程的预计到达时间.我需要等待地理编码器返回值.

I'm trying to get the ETA of trips using addresses with google API. I need to wait for the geocoder to return the value.

我试过使用 await 但它什么也没做.也尝试过使用 defer,但它说它不存在.

I've tried using await but it does nothing. Tried using defer too, but it says that it doesn't exist.

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();
    });
  }

}

这是我得到的错误:未捕获(承诺):类型错误:无法读取未定义的属性纬度"此错误的原因是 this.origin 仍未定义.

This is the error I'm getting: Uncaught (in promise): TypeError: Cannot read property 'lat' of undefined Reason for this error is that this.origin remains undefined.

推荐答案

在提供的示例中,已解决的 promise 返回 nothing,因为这里预期返回 LatLng 值是一个修改版本:

In the provided example a resolved promise returns nothing, since it is expected to return LatLng value here is a modified version:

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:

The below example demonstrates how to utilize Geocoder API with angular-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));
          }
        }
      );
    });
  }
}

这篇关于如何等待谷歌地理编码返回响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆