2
votes

I am trying to implement google places model list in angular 6 with material, I am calling the google places API but I am getting CORS issue like below,

Failed to load https://maps.googleapis.com/maps/api/place/autocomplete/json?input=hy&language=en Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost:4200' is therefore not allowed access.

my code is like below,

<mat-form-field>
        <mat-autocomplete #auto="matAutocomplete" (optionSelected)="selectedUserPlace($event)">
          <mat-option *ngFor="let place of listOfPlaces" [value]="place.description">
            {{place.description}}
          </mat-option>
        </mat-autocomplete>
        <input type="text" aria-label="Number" required (input)="getUserPLaces($event.target.value)" matInput 
           [matAutocomplete]="auto">
<mat-form-field>

getUserPLaces(value: any) {
    this.searchLocationService.loadUserPlaces(value, this.latitude, this.longitude).subscribe(
      (data) => {
        this.listOfPlaces = data['predictions'];
      }
    );
  }

loadUserPlaces(key, latitude, longitude){
    return this.httpClient.get(`https://maps.googleapis.com/maps/api/place/autocomplete/json?input=${key}&language=en`);
  }

How to resolve cors issue here, I know that by disabling chrome security features and some extensions we can avoid this issue. Since my application will go to production and i want to solve this issue through code.

Any solutions will be appreciated.

1
The key prop should be like key=YOUR_API_KEY - Michael

1 Answers

0
votes

Yea, it's a CORB issue, which is different from CORS, just setting the header, will return an error like this:

Access to XMLHttpRequest at 'https://maps.googleapis.com/maps/api/geocode/json?address=407%20N.%205th%20Ave.,%20Ann%20Arbor,%20MI,%2048104&key=AIzaSyBZAcZpANtMgkAuelnkHK1WkImpBECm4WY' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response.

I've been looking for a clear answer on this, the closest I've come is using a reference tag like /// <reference types="@types/googlemaps" /> and even that is not working, although it satisifies errors, google is still undefined for some reason, If you make any progress let me know.