本文介绍了如何使用 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 = "xxxxxxxxx";
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>

现在返回一个错误:

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 访问 googles maps 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 06:51