我试图通过JSON url请求从谷歌地图距离矩阵api获取数据,解析数据并将其放入输入字段以进入我的mysql数据库。我能够完成请求,JSON数据显示在我的Chrome控制台中,但是我得到了#34; Uncaught SyntaxError:意外的令牌:"没有任何东西被放入输入字段。
这是我的代码:
$("button").click(function(){
$.ajax({
url: "https://maps.googleapis.com/maps/api/distancematrix/json",
type: "GET",
dataType: 'jsonp',
cache: false,
data: {
units: "metric",
origins: $("#autocomplete").val(),
destinations: $("#fullAddress").val(),
key: "mykey"
},
success: function(data) {
var json = JSON.parse(data);
var distance = json[distance.value];
$('#distance').val(data);
}
});
});
答案 0 :(得分:0)
错误:Uncaught SyntaxError: Unexpected token :
表示API不支持JSONP
。
如果我将JSONP
更改为JSON
,我会收到其他错误:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin is therefore not allowed access.
Google的Web服务旨在从服务器中使用。如果您想通过客户端上的javascript访问它们,请使用Google Maps Javascript API v3 Distance Matrix Service
代码段
function initialize() {
var service = new google.maps.DistanceMatrixService();
$("#button").click(function() {
service.getDistanceMatrix({
origins: [$("#autocomplete").val()],
destinations: [$("#fullAddress").val()],
travelMode: 'DRIVING',
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function(response, status) {
if (status !== 'OK') {
alert('Error was: ' + status);
} else {
var originList = response.originAddresses;
var destinationList = response.destinationAddresses;
var outputDiv = document.getElementById('output');
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
outputDiv.innerHTML += originList[i] + ' to ' + destinationList[j] +
': ' + results[j].distance.text + ' in ' +
results[j].duration.text + '<br>';
}
}
var distance = response.rows[0].elements[0].distance.text;
$('#distance').val(distance);
}
});
});
}
google.maps.event.addDomListener(window, "load", initialize);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<input id="button" type="button" value="click" />
<input id="autocomplete" value="New York, NY" />
<input id="fullAddress" value="Newark, NJ" />
<div id="output"></div>
<input id="distance" />