Gunderson Gunderson - 10 months ago 151
AngularJS Question

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', [
function($scope, $http){
$scope.userLocation = [];
$scope.currentLocation = function() {
method: 'GET',
url: ''
}).then(function successCallback(response) {

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

XMLHttpRequest cannot load…5.1458888&type=bar&key=xxx. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '' 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" : "",
"id" : "578bfba1f17b0c5fbdafd5b71600b50d3e95c1ca",
"name" : "Ruby Tuesday",
"opening_hours" : {
"open_now" : true,
"weekday_text" : []

Answer Source

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:

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

Hope it helps!