58

I am using Google Place API.

What I want to get suggestion of place for type helping.

So, what I have done is-

var Google_Places_API_KEY = "AIzaSyAK08OEC-B2kSyWfSdeCzdIkVnT44bcBwM";      //Get it from - https://code.google.com/apis/console/?noredirect#project:647731786600:access
var language = "en";        //'en' for English, 'nl' for Nederland's Language


var Auto_Complete_Link = "https://maps.googleapis.com/maps/api/place/autocomplete/json?key="+Google_Places_API_KEY+"&types=geocode&language="+language+"&input=Khu";
$.getJSON(Auto_Complete_Link , function(result)
{
    $.each(result, function(i, field)
    {
        //$("div").append(field + " ");
        //alert(i + "=="+ field);
        console.error(i + "=="+ field);
    });
});

So in what link I am requesting is -

https://maps.googleapis.com/maps/api/place/autocomplete/json?key=AIzaSyAK08OEC-B2kSyWfSdeCzdIkVnT44bcBwM&types=geocode&language=en&input=Khu

And if I go to this link with browser, I can get output like it (please try to ck)-

11

But if I try with jQuery's .getJSON or .ajax, I am getting my request blocked with this message-

222.

SO the XMLHTTPRequest is blocked because of -

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

I have checked in StackOverflow for this problem solution and go through here and here, but can't get my solution perfectly.

Can anyone please enlighten me?

2

8 Answers 8

22

I got it working after finding answer by @sideshowbarker here:

No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

And then used this approach to get it working:

const proxyurl = "https://cors-anywhere.herokuapp.com/";
const url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${latitude},${longitude}&radius=500&key=[API KEY]"; // site that doesn’t send Access-Control-*
fetch(proxyurl + url) // https://cors-anywhere.herokuapp.com/https://example.com
.then(response => response.json())
.then(contents => console.log(contents))
.catch(() => console.log("Can’t access " + url + " response. Blocked by browser?"))

More info can be found in the answer in link above.

4
  • Missing required request header. Must specify one of: origin,x-requested-with Commented Apr 7, 2018 at 11:56
  • you can also simply do the jquery request: jQuery.getJSON( proxyurl+googlemapsurl, function( data ) {}); Thanks for the solution Commented Apr 19, 2020 at 10:40
  • 1
    Doesn't works now.
    – Kunal Raut
    Commented Apr 30, 2021 at 3:37
  • 1
    Dosen't work anymore.
    – Becca
    Commented Jul 7, 2021 at 11:59
9

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);                   
            }           
        });    
5
  • 36
    doesn't work for me either, the problem seems to be that google gives you json but you try dataType:jsonp which gives me error
    – m0j1
    Commented Dec 1, 2015 at 21:03
  • 5
    gives me an error when i run jsonp. The JSON isn't well formed when it comes back this way.
    – Joel
    Commented Jul 18, 2017 at 23:57
  • 3
    doesn't work! So far I knew Google's api only works with json and xhtml
    – sphoenix
    Commented Apr 6, 2018 at 2:27
  • 3
    This doesn't work anymore. No errors so far but the alert method doesn't print anything.
    – piepi
    Commented Apr 14, 2018 at 18:20
  • 5
    Doesn't work anymore Commented May 2, 2018 at 10:44
8

Google provides API Client library:

<script src="https://apis.google.com/js/api.js" type="text/javascript"></script>

It can do google API requests for you, given the API path and parameters:

var restRequest = gapi.client.request({
  'path': 'https://people.googleapis.com/v1/people/me/connections',
  'params': {'sortOrder': 'LAST_NAME_ASCENDING'}
});

Since the library is served from google domain, it can safely call google API's without CORS issues.

Google docs on how to use CORS.

1
  • 3
    For some reason this doesn't work with requests to https://maps.googleapis.com/maps/api/place/details/json. I am getting a 404.
    – Aleksandar
    Commented Aug 20, 2017 at 5:27
4

ok so this is how we do it in javascript... google have their own functions for this....

link: https://developers.google.com/maps/documentation/javascript/places#place_search_requests

var map;
var service;
var infowindow;

function initialize() {
  var pyrmont = new google.maps.LatLng(-33.8665433,151.1956316);

  map = new google.maps.Map(document.getElementById('map'), {
      center: pyrmont,
      zoom: 15
    });

  var request = {
    location: pyrmont,
    radius: '500',
    types: ['store']
  };

  service = new google.maps.places.PlacesService(map);
  service.nearbySearch(request, callback);
}

function callback(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    for (var i = 0; i < results.length; i++) {
      var place = results[i];
      createMarker(results[i]);
    }
  }
}

anyone wants to gain access to the place Id and stuff this is how we do it.... In the call back function we have the JSONArray of places returned by google... In the call back function inside the for loop after the line var place = results[i]; u can get wat u want like

console.log(place.name);
console.log(place.place_id);
var types = String(place.types);
types=types.split(",");
console.log(types[0]);
3

There's no way in client side we using ajax fetching Google Place API, neither use jsonp(syntax error :) nor we met cors issue,

The only way in client side is using Google Javascript Library instead https://developers.google.com/maps/documentation/javascript/tutorial

Or you can fetch google place api in server side, then create your own api for your client side.

3

I was able to solve the problem by creating a PHP file on the same server as my javascript file. Then using cURL to get the data from Google and send it back to my js file.

PHP File

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://maps.googleapis.com/maps/api/place/textsearch/xml?query=" . $_POST['search'] . "&key=".$api);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
echo $output;

Javascript File

var search = encodeURI($("#input_field").val());
$.post("curl.php", { search: search }, function(xml){
  $(xml).find('result').each(function(){
    var title = $(this).find('name').text();
    console.log(title);
  });
});

With this solution I don't get any CORS errors.

0
2

Hi,

Please try with Google distance matrix

    var origin = new google.maps.LatLng(detectedLatitude,detectedLongitude);       
    var destination = new google.maps.LatLng(latitudeVal,langtitudeVal);
    var service = new google.maps.DistanceMatrixService();
    service.getDistanceMatrix(
      {
        origins: [origin],
        destinations: [destination],
        travelMode: 'DRIVING',            
        unitSystem: google.maps.UnitSystem.METRIC,
        durationInTraffic: true,
        avoidHighways: false,
        avoidTolls: false
      }, response_data);

      function response_data(responseDis, status) {
      if (status !== google.maps.DistanceMatrixStatus.OK || status != "OK"){
        console.log('Error:', status);
        // OR
        alert(status);
      }else{
           alert(responseDis.rows[0].elements[0].distance.text);
      }
  });

If you are using JSONP, sometimes you will get missing statement error in the CONSOLE.

Please refer this document click here

1
  • Sometimes Google API did not allow to find the distance without departure Time. You will get error message like "departure_time is in the past. Traffic information is only available for future and current times". Please add the "drivingOptions" Commented Nov 16, 2016 at 15:41
1

I accessed the google maps API like this

    $scope.getLocationFromAddress = function(address) {
    if($scope.address!="Your Location"){
        $scope.position = "";
        delete $http.defaults.headers.common['X-Requested-With'];
        $http(
                {
                    method : 'GET',
                    url : 'https://maps.googleapis.com/maps/api/geocode/json?address='+ address+'&key=AIzaSyAAqEuv_SHtc0ByecPXSQiKH5f2p2t5oP4',

                }).success(function(data, status, headers, config) {

            $scope.position = data.results[0].geometry.location.lat+","+data.results[0].geometry.location.lng;                              
        }).error(function(data, status, headers, config) {
            debugger;
            console.log(data);
        });
    }
}
1
  • 7
    That's the geocode api, it works fine with JS. The place/autocomplete api doesn't.
    – ThadeuLuz
    Commented Feb 22, 2017 at 17:53

Not the answer you're looking for? Browse other questions tagged or ask your own question.