如何在google map api中使用ajax?

时间:2017-02-06 05:31:25

标签: javascript jquery ajax google-maps google-maps-api-3

当我尝试使用ajax从谷歌地图Place API获取json时,我收到this错误。我尝试使用var baseAPIUrl = 'https://maps.googleapis.com/maps/api/directions/json?'; $.ajax({ url: baseAPIUrl += "origin=place_id:" + placeId[0] + "&destination=place_id:" + placeId[1] + apikey, type: "GET", dataType: "json", crossDomain: true, success: function(data) { do something.. } } "row",但他们根本没有工作。这是我下面的ajax代码。

divs

我试图从网址获取方向作为json并使用方向信息做一些事情。有什么想法吗?谢谢!

2 个答案:

答案 0 :(得分:0)

首先,你有一个错字:

url: baseAPIUrl + "origin=place_id:" + placeId[0] + "&destination=place_id:" + placeId[1] + apikey,

不应该是baseAPIUrl +=而是baseAPIUrl +

其次,您无法访问域外的URL(在本例中为localhost)。

在此处阅读:https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy

简而言之,您需要向服务器发出ajax请求,而您的服务器会向google api发出请求。

答案 1 :(得分:0)

尝试这样的事情:

$(document).ready(function(){
    $.ajax({
        url: 'mapProcess.php',                        
        type: 'POST',                                  
        data: {
            var1  :val1   // parameter
        },
        success: function(response){    // response from mapProcess.php
            // do your stuff here
        }
    });
});

腓:

$url = "https://maps.googleapis.com/maps/api/geocode/json?address=".$address."&components=country:IN&key=your_key";

// CURL call to get data from API
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$APIresponse = curl_exec($ch);

curl_close($ch);

$resp = json_decode($APIresponse, true);
相关问题