Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.8 kB
1
Indexable
Never
  getLocationFromAddress$(postCode: string, firstLineOfAddress?: string): Observable<AALocation> {
    return from(this.getLocationFromAddress(postCode, firstLineOfAddress));
  }

  async getLocationFromAddress(postCode: string, firstLineOfAddress?: string): Promise<AALocation> {
    const geocoder = new google.maps.Geocoder();
    postCode = postCode.trim().replace(/\s+/g, ' ').toUpperCase();

    return new Promise((resolve, reject) => {
      const address = firstLineOfAddress ? `${firstLineOfAddress}, ${postCode}` : postCode;
      geocoder.geocode(
        {
          address,
          componentRestrictions: { country: 'UK' },
        },
        (results, status) => {
          if (status === 'OK') {
            const slicedPostCode = new RegExp(postCode.replace(/\s.*$/, '').slice(0, 4), 'i');
            if (slicedPostCode.test(results[0].formatted_address)) {
              resolve({
                latitude: results[0].geometry.location.lat(),
                longitude: results[0].geometry.location.lng(),
              });
            } else if (firstLineOfAddress) {
              resolve(this.getLocationFromAddress(postCode));
            } else {
              reject({ error: status });
            }
          } else if (status === 'ZERO_RESULTS' && firstLineOfAddress) {
            resolve(this.getLocationFromAddress(postCode));
          } else {
            reject({ error: status });
          }
        }
      );
    });
  }

  getPoliciesDetails(): Observable<ICustomerDetails> {
    return this.http.get<ICustomerDetails>(this.envService.customerPoliciesURL).pipe(
      map((value: any) => value.customerDetails as ICustomerDetails),
      catchError(() => of(null))
    );
  }
}