1

New to angular, trying to setup a very simple application using the Google Maps / Places API.

I can successfully use the geolocation service with:

.controller('MainCtrl', [
  '$scope',
  '$http',
  function($scope, $http){
     $scope.userLocation = [];
     $scope.currentLocation = function() {
       $http({
         method: 'GET',
         url: 'https://www.googleapis.com/geolocation/v1/geolocate?key=xxx'
    }).then(function successCallback(response) {
      $scope.userLocation.push(response);
    });
   }
}])

Problem: When I try a similar GET request to their Places API - I get CORS errors:

XMLHttpRequest cannot load https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=36.23…5.1458888&type=bar&key=xxx. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://0.0.0.0:3000' is therefore not allowed access.

Question: Am I able to make these types of requests from Angular or do I need to setup the backend to make that call instead?

I tried using JSONP as the method, which passed the CORS issue, but then I have the problem of not being able to access the data. Not sure if it's invalid JSON... but it says Unexpected identifier :, and when I view the source it looks like perfectly fine data to me:

{
   "html_attributions" : [],
   "results" : [
      {
         "geometry" : {
            "location" : {
               "lat" : 36.2388477,
               "lng" : -115.1540073
            },
         },
         "icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png",
         "id" : "578bfba1f17b0c5fbdafd5b71600b50d3e95c1ca",
         "name" : "Ruby Tuesday",
         "opening_hours" : {
            "open_now" : true,
            "weekday_text" : []
         },
xomena
  • 31,125
  • 6
  • 88
  • 117
Gunderson
  • 3,263
  • 2
  • 16
  • 34

3 Answers3

1

You can use Places API on client side via the library included in Google Maps JavaScript API.

Please refer to this page to figure out how it works:

https://developers.google.com/maps/documentation/javascript/places

Otherwise, you have to create your backend server to send requests to Google and pass response to your client side code.

Hope it helps!

xomena
  • 31,125
  • 6
  • 88
  • 117
  • Referring the OP to the documentation when he asked a specific question that the documentation does not address is entirely unhelpful. – nageeb Jul 19 '18 at 14:58
  • Why documentation doesn't explain the subject? You cannot use web service via AJAX call, because Google doesn't set CORS headers on their side, so the only option is using places libraries of Maps JavaScript API. Isn't it clear? I believe documentation is quite well written. – xomena Jul 19 '18 at 20:46
0

After research I found the below solution. It worked on angular 11. Some google get api gives CORS issues so to resolve that you need to install below npm package

npm install axios

In the sevice.ts file
const axios = require('axios');

getTimeZone(latitude: any, longitude: any): any {
console.log("lat", latitude);

const url1 =
  `https://maps.googleapis.com/maps/api/timezone/json?location=` +
  latitude +
  "," +
  longitude +
  `&timestamp=1331161200&key=` +
  this.googleApiKey;
const config = {
  method: "get",
  url: url1,
  headers: {},
};
return new Observable<any>((observer) => {
  axios(config)
    .then(function (response: any): void {
      observer.next(response.data);
      // return response.data;
    })
    .catch(function (error: any): void {
      observer.next(error);
    });
});

}

in component.ts file

getTimezoneVal(lat: any, long: any): void {
    this.lat = lat;
    this.long = long;
    this.googleAddressService.getTimeZone(lat, long).subscribe(
      (res: any) => {
        console.log("res", res);
})

}

In component file you will get response and CORS issue will get resolved.... Thanks.... Vikas Anand

Dharman
  • 30,962
  • 25
  • 85
  • 135
-3

I think JSONP may work in this situation, Jsonp helps for cross domain issues.

Atul Jindal
  • 946
  • 8
  • 8