Home » Javascript » TypeError: gapi.auth2.getAuthInstance(…) is null

TypeError: gapi.auth2.getAuthInstance(…) is null

Posted by: admin November 1, 2017 Leave a comment

Questions:

I’m trying to write a tool that uses the Google Distance Matrix API,
but I keep running into authorization issues. I’ve been working from
the following examples (to no avail):

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

At first, I kept encountering a CORS error, which I tried to fix using
an OAuth token, but now I’m getting the error 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>

I’ve tried everything I can think of; what am I doing wrong here?

Answers: