【问题标题】:How can I use ajax with google map api?如何将 ajax 与谷歌地图 api 一起使用?
【发布时间】:2017-06-22 23:44:24
【问题描述】:

当我尝试使用 ajax 从 google map Place API 获取 json 时,我收到 this 错误。我尝试使用jsonpbeforeSend,但它们根本不起作用。这是我下面的ajax代码。

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..
            }
}

我正在尝试从 url 作为 json 获取方向,并使用方向信息做一些事情。有什么想法可以做到这一点吗?谢谢!

【问题讨论】:

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


    【解决方案1】:

    首先,你有一个错字:

    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 发出请求。

    【讨论】:

    • 谢谢我照你说的做了
    【解决方案2】:

    试试这样的:

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

    PHP:

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

    【讨论】:

    • 为什么要使用php?
    • 因为您无法访问域外的 URL。您必须对服务器进行 ajax 调用,这将对谷歌 API 进行 CURL 调用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-17
    相关资源
    最近更新 更多