CORS and Angular $http GET to Google Places API

2020-02-07 07:36发布

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" : []
         },

2条回答
趁早两清
2楼-- · 2020-02-07 07:59

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!

查看更多
▲ chillily
3楼-- · 2020-02-07 08:12

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

查看更多
登录 后发表回答