使用Google Direction API,Access-Control-Allow-Origin不允许使用原始网址

net*_*djw 2 jquery access-control google-maps-api-3

我知道这个问题已经被问到并回答了,但它对我没有帮助.

这是我的jQuery代码:

var gmapsurl = 'http://maps.googleapis.com/maps/api/distancematrix/json?'+
                            'origins='+addr_origin+
                            '&destinations='+addr_destination+
                            '&mode=driving&language=hu&units=metric'+
                            '&key='+mykey+
                            '&sensor=false';
$.getJSON(gmapsurl, function(data) {
    alert( 'OK' );
});
Run Code Online (Sandbox Code Playgroud)

现在我Origin (my site url) is not allowed by Access-Control-Allow-Origin.在浏览器中收到错误消息.但是如果我将这个url直接写入浏览器,那么我会得到一个JSON结构.

我怎样才能解决这个问题?

pov*_*asp 11

您应该使用Google Maps API进行地理编码:

var geocoder = new google.maps.Geocoder();
var geocoderRequest = { address: "MountainView, CA" };
geocoder.geocode(geocoderRequest, function(results, status){
//do your result related activities here, maybe push the coordinates to the backend for later use, etc.
});
Run Code Online (Sandbox Code Playgroud)

而不是通过JSON调用服务.当然,您应该在脚本中包含此内容以使用Google Maps API:

<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
Run Code Online (Sandbox Code Playgroud)