Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
776 views
in Technique[技术] by (71.8m points)

angularjs - CORS and Angular $http GET to Google Places API

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" : []
         },
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...