How to Use Cors to Implement JavaScript Google Places API Request

How to use CORS to implement JavaScript Google Places API request

You are trying to use the Google Places API Web Service on client side whereas it is designed for server side applications. That's probably why appropriate CORS response headers are not set by the server.

As explained in the Notes at the beginning of the Place Details documentation, you should use the Places Library in the Google Maps JavaScript API:

If you're building a client-side application, take a look at the Google Places API for Android, the Google Places API for iOS, and the Places Library in the Google Maps JavaScript API.

Note: you will need to enable the Google Maps JavaScript API in your Google Developer Console first.

Here is a way you can proceed to get place details (based on the example from the documentation):

<head>
<script type="text/javascript">
function logPlaceDetails() {
var service = new google.maps.places.PlacesService(document.getElementById('map'));
service.getDetails({
placeId: 'ChIJN1t_tDeuEmsRUsoyG83frY4'
}, function (place, status) {
console.log('Place details:', place);
});
}
</script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAW4CQp3KxwYkrHFZERfcGSl--rFce4tNw&libraries=places&callback=logPlaceDetails"></script>
</head>
<body>
<div id="map"></div>
</body>

Google Place details output to the console

CORS issue with JavaScript accessing google places API

To access the places API from javascript use the Google Maps Javascript API v3 places library.

Google places API CORS error

As @geocodezip mentioned, rather than making another AJAX call, use the places library already included. Just make sure it's included in the query string like:

src="https://maps.googleapis.com/maps/api/js?key=[MY_KEY]&libraries=places" async defer

Then you'll have .getDetails() available for use.

    var request = {
placeId: 'ChIJN1t_tDeuEmsRUsoyG83frY4'
};
service = new google.maps.places.PlacesService(map);
service.getDetails(request, callback);

function callback(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
createMarker(place);
}
}

Google Place API - No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access

AJAX Requests are only possible if port, protocol and domain of sender and receiver are equal,if not might lead to CORS. CORS stands for Cross-origin resource sharing and has to be supported on the server side.

Solution

JSONP

JSONP or "JSON with padding" is a communication technique used in JavaScript programs running in web browsers to request data from a server in a different domain, something prohibited by typical web browsers because of the same-origin policy.

Something like this might help you mate.. :)

$.ajax({
url: Auto_Complete_Link,
type: "GET",
dataType: 'jsonp',
cache: false,
success: function(response){
alert(response);
}
});

CORS and Google Maps Places Autocomplete API calls

The supported way to call the Place Autocomplete API from a web app is using the Places library:

<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -33.8688, lng: 151.2195},
zoom: 13
});
...
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(card);
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var infowindowContent = document.getElementById('infowindow-content');
infowindow.setContent(infowindowContent);
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
</script>
<script
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap"
async defer></script>

That way it doesn’t matter that the responses lack the Access-Control-Allow-Origin header.

Using the Maps JavaScript API that way—by way of a script element to load the library, and then using the google.maps.Map and other google.maps.* methods—is the only supported way. Google intentionally does not allow doing it by way of requests sent with XHR or the Fetch API.

Sending a details request to Google Places API - (CORS error)

You need to use a server side proxy to prevent this error. It works when you access the url directly because you have no origin when you do that.

  • JS AJAX request to local server -> remote server, request received, response sent, remote server -> local server -> AJAX request to JS.

Check this related SO question:

  • What to do when an API doesn't allow Access-Control-Allow-Origin
  • webpack dev server CORS issue

You can either modify your API server so that CORS is enabled, or follow the instructions on the webpack-dev-server page under "Combining with an existing server" to combine asset serving with webpack-dev-server and your own API server.

  • How do I make a CORS request with fetch on my localhost?

Hope this helps!



Related Topics



Leave a reply



Submit