如何使用jQuery从谷歌方向api获取JSON? [英] How do I get JSON from google directions api using jQuery?

查看:98
本文介绍了如何使用jQuery从谷歌方向api获取JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery.getJSON demo</title>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<script>
APIKEY = "AIzaSyC1CCvx0HI78PGLWpO-R67s8r7A0zckEyc";
requestURL = "https://maps.googleapis.com/maps/api/directions/json?origin=Brooklyn&destination=Queens&mode=transit&key=" + APIKEY + "callback=?";

$.ajax({
            url: requestURL, 
            type: "GET",   
            dataType: 'jsonp',
            cache: false,
            success: function(response){                          
                alert(response);                   
            }           
        }); 
</script>

</body>
</html>

现在,这会返回一个错误:

Right now this is returning an error of:

https://maps.googleapis.com/maps/api/directions/json?origin=Brooklyn&destin…=Queens&mode=driving&key=[APIKEYHERE]&callback=?
maps.googleapis.com/maps/api/directions/json?origin=Brooklyn&destination=Qu…l7pA&callback=jQuery1102013888467964716256_1429822392524&_=1429822392525:2 Uncaught SyntaxError: Unexpected token :

我无法弄清楚如何让它起作用。 API密钥目前是一个浏览器API密钥。

I can't figure out how to get it to work. The API key is currently a browser API key.

推荐答案

您无法使用ajax访问Google地图API。它会给你一个未知的错误响应,但实际上它是由CORS引起的拒绝访问。
以下代码将为您提供布鲁克林与皇后之间路线的有效数据,以指标为依据驾驶


You cannot use ajax to access googles maps api. It will give you an unknown error response but in reality its an "access denied" due to CORS. The below code will give you valid data for the route between brooklyn and queens, driving, in metrics

<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
        var directionsService = new google.maps.DirectionsService();
        var directionsRequest = {
            origin: "brooklyn",
            destination: "queens",
            travelMode: google.maps.DirectionsTravelMode.DRIVING,
            unitSystem: google.maps.UnitSystem.METRIC
        };
        directionsService.route(directionsRequest, function (response, status) {
            if (status == google.maps.DirectionsStatus.OK) {                    
            //do work with response data
            }
            else
                //Error has occured
        })

参考: http:// www.sitepoint.com/find-a-route-using-the-geolocation-and-the-google-maps-api/

这篇关于如何使用jQuery从谷歌方向api获取JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆