Your code is calling gapi.client.plus.people.get
method before loading the google api library https://plus.google.com/js/client:plusone.js
. Hence you are getting gapi is not defined error.
Approach to work-
- Why its not working?
We are calling https://plus.google.com/js/client:plusone.js
asynchronously(non blocking) to improve the performance. With Async javascript file loading, you are not able to call the gapi method on body load.
<script type="text/javascript">
(function() {
var po = document.createElement('script');
po.type = 'text/javascript'; po.async = true;
po.src = 'https://plus.google.com/js/client:plusone.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(po, s);
</script>
- To make the api call you first have to know javascript file is successfully loaded.
For this you have to call method using callback.
https://apis.google.com/js/client:plusone.js?onload=makeAPICall
Write an api request & execution it in the callback method to get data.
Check below example for this-
<html>
<head></head>
<body>
<span id="signinButton">
<span
class="g-signin"
data-callback="signinCallback"
data-clientid="YOUR CLIENT ID.apps.googleusercontent.com"
data-cookiepolicy="single_host_origin"
data-scope="https://www.googleapis.com/auth/plus.login">
</span>
</span>
<script type="text/javascript">
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/client:plusone.js?onload=signinCallback';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
function signinCallback(authResult) {
if (authResult['status']['signed_in']) {
document.getElementById('signinButton').setAttribute('style', 'display: none');
makeAPICall();
} else {
console.log('Sign-in state: ' + authResult['error']);
}
}
function makeAPICall(){
gapi.client.load('plus', 'v1', function() {
var request = gapi.client.plus.people.get({
'userId': 'me'
});
request.execute(function (resp){
console.log(resp);
if(resp.id){
console.log('ID: ' + resp.id);
}
if(resp.displayName){
console.log('Display Name: ' + resp.displayName);
}
if(resp.image && resp.image.url){
console.log('Image URL: ' + resp.image.url);
}
if(resp.url){
console.log('Profile URL: ' + resp.url);
}
});
});
}
</script>
</body>
</html>
Conclusion: Calling javascript API before loading the asynchronously client library.
To avoid "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.". Call makeAPICall() method only when user is logged in not on every request.