Google Place API - No 'Access-Control-Allow-Or

2019-01-06 18:33发布

问题:

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)-

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

.

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, [here4 and here, but can't get my solution perfectly.

Can anyone please enlighten me?

回答1:

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);                   
            }           
        });    


回答2:

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:

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.



回答4:

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.



回答5:

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);
        });
    }
}


回答6:

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.



回答7:

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



回答8:

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.