Google 地点 API - 请求的资源上不存在 'Access-Control-Allow-Origin' header。因此不允许来源 'null' 访问

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

我正在使用 Google 地方 API.

我想获得有关类型帮助的建议。

所以,我所做的是-

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

所以 link 我要求的是 -

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

如果我用浏览器访问这个 link,我可以获得类似的输出(请尝试 ck)-

但是如果我尝试使用 jQuery 的 .getJSON.ajax,我会得到我的请求被这条消息阻止了-

.

所以 XMLHTTPRequest 被阻止是因为 -

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

我已经签到Whosebug for this problem solution and go through here and here,但无法完美地得到我的解决方案。

谁能赐教吗?

AJAX 只有发送方和接收方的端口、协议和域相等时才可以请求,否则可能会导致 CORS。 CORS代表跨源资源共享,服务器端必须支持。

Solution

JSONP

JSONP 或 "JSON with padding" 是 Web 浏览器中 JavaScript 程序 运行 中使用的一种通信技术,用于从不同域中的服务器请求数据,这是典型的 Web 浏览器所禁止的,因为同源策略。

这样的事情可能会帮助你交配.. :)

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

好的,这就是我们在 javascript 中的做法... google 有自己的功能....

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

任何人都想获得对地点 ID 和内容的访问权,这就是我们的做法....在回调函数中,我们有 google 返回的地点的 JSONArray...在调用中在行 var place = results[i]; 之后的 for 循环内的返回函数你可以得到你想要的东西

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

我像这样访问了 google 地图 API

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

嗨,

请尝试使用 Google 距离矩阵

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

如果您使用的是 JSONP,有时您会在 CONSOLE 中收到缺少语句的错误。

请参考此文档click here

Google 提供 API 客户端库:

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

给定 API 路径和参数,它可以为您执行 google API 请求:

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

由于库是从 google 域提供的,它可以安全地调用 google API 而不会出现 CORS 问题。

Google docs on how to use CORS.

我们无法在客户端使用 ajax 获取 Google Place API,既没有使用 jsonp(语法错误 :),也没有遇到 cors 问题,

客户端的唯一方法是使用 Google Javascript 库 https://developers.google.com/maps/documentation/javascript/tutorial

或者您可以获取 google 将 api 放在服务器端,然后为您的客户端创建您自己的 api。

我能够通过在与我的 javascript 文件相同的服务器上创建一个 PHP 文件来解决问题。然后使用 cURL 从 Google 获取数据并将其发送回我的 js 文件。

PHP 文件

$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 文件

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

使用此解决方案,我没有收到任何 CORS 错误。

我在这里找到@sideshowbarker 的答案后开始工作:

然后使用这种方法让它工作:

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

更多信息可以在上面 link 的答案中找到。