I'm using the following repo https://github.com/egeloen/ivory-google-map/ to get data from google maps.
I have the coordinates and i want to get the data from them. (Address, City, Country etc)
Code
$geocoder = new GeocoderService(
new Client(),
new GuzzleMessageFactory()
);
$geocoder->setKey("api key");
$request = new GeocoderCoordinateRequest(new Coordinate(38.01008020608845, 23.728229105472565));
$response = $geocoder->geocode($request);
print_r($response);
Every time i run the following code i get a status of REQUEST_DENIED.
I have enabled to my API the Geocoding API.
I have searched the documentation but i don't know where is the problem.
Any suggestions?
I just found out that my API key had a referrer restriction.
The referrer restriction is for client-side request. I just created a new API key with no referrer restriction and everything worked.
Related
I know how to access Google Analytics data with Data Studio or with Google Apps script in Javascript:
var account = Analytics.Management.Accounts.list().items[0];
var webProperties = Analytics.Management.Webproperties.list(account.id);
...
var report = Analytics.Data.Ga.get(tableId, startDate, endDate, metric,
options);
But in PHP, how is it possible to retrieve the number of visitors of a specific website or specific page, from a Google Analytics account / property / view? i.e.:
input: analytics account login/password/website code 'UA-XXXXX-Y'
output: [19873, 17873, 13999, 21032, ..., 16321] (i.e. the number of visits on www.example.com for each of the 30 last days, as a list of integers or JSON)
You can use Google Analytics API client in PHP.
Google analytic api client library
You can use the Query Explorer to create the queries to check.
Code Example:
$analytics = new analytics('username', 'password');
$analytics->setProfileByName('user.name');
//set the date range for which you want stats for
$analytics->setMonth(date('n'), date('Y'));
// it could also be $analytics->setDateRange('YYYY-MM-DD', 'YYYY-MM-DD'))
print_r($analytics->getVisitors());
print_r($analytics->getPageviews());
The above example used the Google Analytics API client in PHP. It was the first library released in PHP. Six years later, this software is outdated. Google changed the API.
As an alternative you can use GAPI library.
Above is the example how it would work, you can include gapi class to make it functional.
GAPI Analytic Library
Another way is that you can use the Google Analytics Reporting API v4 for PHP.
You can obtain this using composer:
composer require google/apiclient:^2.0
Guide to usage of this library is at github
I use this package:
https://github.com/google/google-api-php-client
You can use it to access all the Google APIs from PHP, including of course Google Analytics
Here's an example of how to use it:
// create client object and set app name
$client = new Google_Client();
$client->setApplicationName('Your app name'); // name of your app
// set assertion credentials
$client->setAssertionCredentials(
new Google_AssertionCredentials(
'your_analytics_email#gmail.com', // email you added to GA
[
'https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents('/your/key/file.p12') // keyfile you downloaded
]
)
);
// other settings
$client->setClientId('your-client-id'); // from API console
$client->setAccessType('offline_access'); // this may be unnecessary?
// create service and get data
$service = new Google_AnalyticsService($client);
$from_date = date("Y-m-d",strtotime("-30 days")); // A month
$to_date = date("Y-m-d");
$response = $service->data_ga->get(
"ga:profile_id", // profile id
"$from_date", // start date
"$to_date", // end date
"ga:uniquePageviews",
[
'dimensions' => 'ga:pagePath', // Dimensions you want to include, pagePath in this example
'sort' => '-ga:uniquePageviews', // Sort order, order by unique page views from high to low in this case
'filters' => 'ga:pagePath=~\/articles\/[a-zA-Z0-9\-]+', // example url filter
'max-results' => '50' // Max results
]
);
foreach ($response["rows"] as $row) {
// ...do whatever you want with the results
}
Also, here's a guide on how to use the Google APIs:
https://developers.google.com/api-client-library/php/start/get_started
EDIT: You need to create credentials to access the Analytics API. You do it here: https://console.cloud.google.com/flows/enableapi?apiid=analyticsreporting.googleapis.com&credential=client_key. You need to register a project first, and then create the credentials. There are three options: API key, OAuth client ID and Service Account Key. I didn't want to use OAuth, so I used the Service Account Key. You can try using the API Key, in which case replace the $client->setAssertionCredentials(...) call for $client->setDeveloperKey(your_api_key). You can't use username and password directly AFAIK.
I've been taking a look at the Google API PHP Client and would like to use it to add rows to a Google Sheet. From the code, it looks like one would use this method:
public function insert($fileId, Google_Service_Drive_Property $postBody, $optParams = array())
{
$params = array('fileId' => $fileId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('insert', array($params), "Google_Service_Drive_Property");
}
but I can't really tell what the parameters would be. Am I heading in the right direction? Also, not quite sure on how to connect to a specific Sheet. Please advise.
Thanks!
Use Google sheets class from zend framework 1.12. They have very nicely coded library for Google Spreadsheets
https://github.com/zendframework/zf1/tree/master/library/Zend/Gdata/Spreadsheets
I figured out how to work this and wanted to share with you guys. As I stated in a comment, I did not think using Zend's GData class was a good way for me since it's very dependent on other classes throughout the framework, thus being too heavy.
So I ended up using this Spreadsheet Client on top of Google's API. Google's API is used to authenticate my service, then I start calling the Spreadsheet Client library afterwards.
After spending over a day of Googling for various problems I had for the authentication process, here's what I did to make things work:
Created a new project for Google API here
Clicked "APIs" menu on the left side under "APIs & Auth"
Searched the Drive API and enabled it (can't remember if it was necessary)
Clicked the "Credentials" menu on the left
Clicked "Create new Client ID" button under OAuth
Selected "Service Account"
After info showed & json downloaded (not needed), I clicked "Generate new P12 Key" button
I saved the p12 file somewhere I could access it through PHP
Then in the code, I added the following lines:
$email = 'somethingsomethingblahblah#developer.gserviceaccount.com';
$CLIENT_ID = $email;
$SERVICE_ACCOUNT_NAME = $email;
$KEY_FILE = 'path/to/p12/file';
$SPREADSHEETS_SCOPE = 'https://spreadsheets.google.com/feeds';
$key = file_get_contents($KEY_FILE);
$auth = new Google_Auth_AssertionCredentials(
$SERVICE_ACCOUNT_NAME,
array($SPREADSHEETS_SCOPE),
$key
);
$client = new Google_Client();
$client->setScopes(array($SPREADSHEETS_SCOPE));
$client->setAssertionCredentials($auth);
$client->getAuth()->refreshTokenWithAssertion();
$client->setClientId($CLIENT_ID);
$accessToken = $client->getAccessToken();
Also, I had to make sure I:
Shared my spreadsheet specifically with the email address on my service account in the code above
Synced my server's time (I'm running Vagrant CentOS so it's slightly different)
I believe you can run this code with other services beyond Spreadsheets, such as Youtube, Analytics, etc., but you will need to get the correct scope link (see $SPREADSHEETS_SCOPE above). Remember, this is only when using the Service Account on the Google Console, which means you are programmatically getting data from your code. If you are looking to have others users sign in using the API, then it's different.
include('GoogleAnalyticsAPI.class.php');
$ga = new GoogleAnalyticsAPI('service');
$ga->auth->setClientId('your_client_id'); // From the APIs console
$ga->auth->setEmail('your_email_addy'); // From the APIs console
$ga->auth->setPrivateKey('/super/secure/path/to/your/privatekey.p12');
$auth = $ga->auth->getAccessToken();
i am getting all values in $ga except AccessToken.I have given all paths,email,client id.if i print $auth, nothing is getting displayed.What should i do to get access token?
I refered this site https://github.com/wanze/Google-Analytics-API-PHP
Thanks in advance.
I have got a successful oauth TripIt granting process using the same methodology that is used to connect and authenticate users against the LinkedIn and Twitter APIs in PHP (PECL Oauth etc).
However, whenever when I do a valid request (ie a 200 response... no 401 nor 404), all I get in response is:
<Response><timestamp>1301411027</timestamp><num_bytes>80</num_bytes></Response>
I want to list the authenticated user's profile and trip data... The API docs (the pdf) is a bit sketchy on how to do this when the actual user id isn't known, but here are the queries I have attempted:
https://api.tripit.com/v1/list/trip
https://api.tripit.com/v1/list/trip/traveler/true
https://api.tripit.com/v1/get/profile
All returning the same response (as part of the oauth class "last response" method). This is where the LinkedIn API response contents can be found... so what is going on with TripIt? :P
It took a bit of experimenting, but here's an example of one that appears to be working to return data.
$response = $TripIt->_do_request('get/profile');
EDIT:
This one is likely the preferred method.
$response = $TripIt->_do_request('get', 'profile');
I've gone one step further and thrown it into an XML parser.
$response = $TripIt->_do_request('get', 'profile');
$profile = new SimpleXMLElement($response);
Here is one I'm using to get past trips. That third parameter is the one to use for filters.
$response = $TripIt->_do_request('list', 'trip', array('past'=>'true' );
$trips = new SimpleXMLElement($response);
I need a function to get an nearest address or city from coordinates(lat,long) using google map api reverse geocoding and php... Please give some sample code
You need to use the getLocations method on the GClientGeocoder object in the Google Maps API
var point = new GLatLng (43,-75);
var geocoder = new GClientGeocoder();
geocoder.getLocations (point, function(result) {
// access the address from the placemarks object
alert (result.address);
});
EDIT: Ok. You are doing this stuff server side. This means you need to use the HTTP Geocoding service. To do this you will need to make an HTTP request using the URL format described in the linked article. You can parse the HTTP response and pull out the address:
// set your API key here
$api_key = "";
// format this string with the appropriate latitude longitude
$url = 'http://maps.google.com/maps/geo?q=40.714224,-73.961452&output=json&sensor=true_or_false&key=' . $api_key;
// make the HTTP request
$data = #file_get_contents($url);
// parse the json response
$jsondata = json_decode($data,true);
// if we get a placemark array and the status was good, get the addres
if(is_array($jsondata )&& $jsondata ['Status']['code']==200)
{
$addr = $jsondata ['Placemark'][0]['address'];
}
N.B. The Google Maps terms of service explicitly states that geocoding data without putting the results on a Google Map is prohibited.
You can display Geocoding API results on a Google Map, or without a
map. If you want to display Geocoding API results on a map, then these
results must be displayed on a Google Map. It is prohibited to use
Geocoding API data on a map that is not a Google map.