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

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-27 01:17:26

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

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

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.

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.

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.

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

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!