Я пытаюсь получить ETA поездок, используя адреса с Google API.
Мне нужно подождать, пока геокодер вернет значение.
Я пытался использовать await, но он ничего не делает.
Пробовал также использовать 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();
});
}
}
Это ошибка, которую я получаю:
Uncaught (в обещании): TypeError: Невозможно прочитать свойство 'lat' из неопределенного
Причиной этой ошибки является то, что this.origin остается неопределенным.