我试图编写一个使用Google Distance Matrix API的工具, 但我一直在遇到授权问题。我一直在工作 以下示例(无效):
https://developers.google.com/api-client-library/javascript/features/cors https://developers.google.com/identity/sign-in/web/devconsole-project https://developers.google.com/maps/documentation/distance-matrix/start
起初,我一直遇到一个CORS错误,我试图修复它
一个OAuth token
,但现在我收到了错误TypeError:
gapi.auth2.getAuthInstance(...) is null
<meta name="google-signin-client_id" content="MY_ID_HERE.apps.googleusercontent.com">
<script src="https://apis.google.com/js/api.js" type="text/javascript"</script>
<script type="text/javascript">
gapi.load('auth2', function() {
// Library loaded.
});
window.onLoadCallback = function(){
gapi.auth2.init({
client_id: "MY_ID_HERE.apps.googleusercontent.com"
});
}
</script>
<script>
function getDistance(){
var ds = document.getElementById("select-duty-station").value;
if(ds == "Choose One" || ds == ""){
alert("Select a Duty Station");
return false;
}
var dc = document.getElementById("text-destination").value;
if(dc == ""){
alert("Destination is empty");
return false;
}
var orig = "origins=" + ds.replace(" ", "+");
var dsts = "destinations=" + dc.replace(" ", "+");
var apiKey = "MY_KEY_HERE";
var url3 = "https://maps.googleapis.com/maps/api/distancematrix/json?" +
orig + "&" + dsts + "&key=" + apiKey;
console.log(url3);
var user = gapi.auth2.getAuthInstance().currentUser.get();
var oauthToken = user.getAuthResponse().access_token;
var client3 = new XMLHttpRequest();
client3.open("GET", url3, false);
client3.onreadystatechange = function() {
if(client3.readyState == 4){
console.log(client3.responseText);
var obj = JSON.parse(client3.responseText);
};
};
client3.setRequestHeader("Authorization", "Bearer " + oauthToken);
client3.send();
}
</script>
我已经尝试过我能想到的一切;我在这做错了什么?
答案 0 :(得分:0)
调用init时,您缺少scope
属性。
window.onLoadCallback = function(){
gapi.auth2.init({
clientId: "MY_ID_HERE.apps.googleusercontent.com"
scope: 'some scope here'
});
可在此处找到GAPI范围参考:https://developers.google.com/identity/protocols/googlescopes
另外,请确保为您的应用程序输入正确的clientId
。
使用Google API Javascript库:
https://developers.google.com/api-client-library/javascript/features/authentication https://developers.google.com/identity/protocols/OAuth2UserAgent