how to use google analytics geo map - google-analytics

i successfully created the linechart how many people visited my site from different countries. here is my code:
var API_KEY = 'MY_API_KEY';
var CLIENT_ID = 'CLIENT_ID';
var TABLE_ID = 'ga:XXX';
gadash.configKeys({
'apiKey': API_KEY,
'clientId': CLIENT_ID
});
var chart1 = new gadash.Chart({
'type': 'LineChart',
'divContainer': 'country_visitors',
'last-n-days':30,
'query': {
'ids': TABLE_ID,
'metrics': 'ga:visits',
'dimensions': 'ga:country'
},
'chartOptions': {
height:600,
title: 'Visitors from countries (Last 30 days)',
hAxis: {title:'Date'},
vAxis: {title:'Visits'},
curveType: 'function'
}
}).render();
but what i need is to show the data in geomap instead of linechart like it shows in dashboard when you log in google analytics account. i tried to change the type to GeoMap but it shows only the table not geo map. i also read the documentation on Visualization: Geomap. what i saw there is i need to give the data in an array and i don't have any idea how to do that. can anyone please help me with what i need? and one more thing when i was generating the line chart it asked me to authorize analytics, what should i do to view the analytics data without logging in. i would really appreciate your help.

Related

Flutter : polylines show straight line

Im implementing a flutter app to display polylines by flutter google maps plugin, But It only shows a straight line between those two points rather than showing actual route, I'm not quite sure what needed to do.
Here my add markers function
void addMarker() {
latlng.add(LatLng(5.973804, 80.429838));
allMarkers.add(Marker(
markerId: MarkerId('busLoc'),
draggable: true,
onTap: () {
print('Marker Tapped');
},
position: LatLng(5.973804, 80.429838),
));
_polyline.add(Polyline(
color: Colors.blue,
visible: true,
points: latlng,
polylineId: PolylineId("distance"),
));
Here my scaffold
GoogleMap(
polylines: _polyline,
markers: Set.from(allMarkers),
initialCameraPosition:
CameraPosition(target: LatLng(widget.la, widget.l0), zoom: 14),
mapType: MapType.normal,
),
And I'll attach screenshot below as well
To get the route from point A to point B you will need to use Directions API that is available on the google_maps_webservice flutter package, which is a service from Google Maps Platform that gives the route information
One of the route information is the overview_polyline that holds an encoded polyline representation of the route.
You can get the overview_polyline by having a function that sends request to Directions API using the google_maps_webservice package like this:
import 'package:google_maps_webservice/directions.dart' as directions;
final _directions = new directions.GoogleMapsDirections(apiKey: "YOUR_API_KEY");
var overviewPolylines;
directions.DirectionsResponse dResponse = await _directions.directionsWithAddress(
_originAddress,
_destinationAddress,
);
if (dResponse.isOkay) {
for (var r in dResponse.routes) {
overviewPolylines = r.overviewPolyline.points
}
}
Then, once you get the overview_polyline from Directions API using the sample code above, you will need to decode it using the PolyUtil(); method from the google_maps_util flutter package like this:
import 'package:google_maps_util/google_maps_util.dart';
PolyUtil myPoints = PolyUtil();
var pointArray = myPoints.decode(overviewPolylines);
Once decoded you can pass the pointArray to your polyline object like this:
_polyline.add(Polyline(
color: Colors.blue,
visible: true,
points: pointArray,
polylineId: PolylineId("distance"),
));
it shows straight line because you have in your polyline only two points, so the expected behavior is to draw a line from one point to the other
you have to use google direction API here is an article explains how to draw route between two points in flutter.
https://medium.com/flutter-community/drawing-route-lines-on-google-maps-between-two-locations-in-flutter-4d351733ccbe

Save location with geofire on an existing document

I want an using firebase real time database to store events of some sort.
An event can have a changing status in its life cycle.
I want to be able to fetch all active events near a user current location.
Because it doesn't seems like geofire enables me to save the location on the event document, I would have to get all events near the location, and then filter by status and given event ids (is that event possible??).
Is there a better way?
Thanks!
Geofire works by returning what's close to coordinates you give it. For an idea or starter template, check out https://getaa.org. (click the map icon top center and enter 'san francisco' or 'baton rouge' if you are in an area with no meetings.
The code is all on github.
Here's a code snippet:
function loadQuery(lat,lng,today){
//console.log('loadQuery function fired with ' + lat,lng,today);
var geoKeys = [];
var records=[];
var geoQuery = geofire.query({
center: [lat,lng],
radius: radius
});
var onKeyEnteredRegistration = geoQuery.on("key_entered", function(key, location, distance) {
geoKeys.push(key);
//console.log('geoQuery event KEY ENTERED with key: ' + key);
});
// GeoKeys now in array
var onReadyRegistration = geoQuery.on("ready", function() {
//console.log('geoQuery event READY');
if(geoKeys.length > 0){
toastUp('Fetching Meetings...');
// Get recordset for each key into sites array
readFirebaseNodes(geoKeys).then(function(value) {
//filter for today
var todaysMeetings = dayFilter(today);
drop(todaysMeetings);
}, function(err) {
//console.log(err); // Error!
});
} else {
toastUp('No area meetings found. You are encouraged to volunteer to add them. Click Meetings Manager to become a site administrator.');
toastDown(2000);
}
});
}
The Firebase Realtime Database can only query on a single property. The fact that GeoFire can filter on two axes (longitude and latitude) is already quite magical (thanks to the use of geohashes). Adding one more value to the mix is beyond what GeoFire is made for.
But it's actually quite simple to only show nearby active events: keep a location/reference in your database with just the locations of those active events. Then you can simply create a GeoFire object on that location, and it will only find nearby active events:
// Create a Firebase reference where GeoFire will store its information
var firebaseRef = firebase.database().ref("activeEventLocations");
// Create a GeoFire index
var geoFire = new GeoFire(firebaseRef);

How to get results from google analytics if a custom dimension is not available for old data?

I am using google analytics api to fetch data from google to make my own dashboard. Recently, I have created a custom dimension for some purpose. There was a lot of data before the creation of custom dimension and i could access it using.
gapi.client.analytics.data.ga.get({
'ids': 'ga:' + profileId,
'start-date': '300daysAgo',
'end-date': 'today',
'metrics': 'ga:users',
'dimensions':'ga:country,ga:region,ga:city,ga:date,ga:operatingSystem,ga:browser'
ا
})
.then(function(response) {
//Dosomething
})`
The code above returned the results for last 300 days. After creating CD i want to access the results for which it is defined as well as for which it isn't.
gapi.client.analytics.data.ga.get({
'ids': 'ga:' + profileId,
'start-date': '300daysAgo',
'end-date': 'today',
'metrics': 'ga:users',
'dimensions':'ga:dimension1,ga:country,ga:region,ga:city,ga:date,ga:operatingSystem,ga:browser'
ا
})
.then(function(response) {
//Dosomething
})
The response however shows 0 rows. Any suggestions?
You cannot fetch data for which the custom dimension is not defined. You are querying based on the new custom dimension which is not available for data previously present. The only way you could do is fetch the data before the custom dimension was defined (if the data is not much) and reinsert it. This way custom dimension would be defined for that data.

Analytics Scripts Insufficient Permission from Google Sheets

I'm trying to write a script to grab Google Analytics data & add it to a Google Sheet.
When running the following code, I get the following error on the sheet:
"User does not have sufficient permissions for this profile."
Just a few quick check-box items:
Yes, I have admin permissions for the Analytics account I'm trying to access
Yes, I have admin permissions for the Google Sheet from which I'm creating the script
Yes, I've double-checked my current Google login to make sure I'm on the right account.
Here is the code:
function runDemo() {
try {
var results = getReportDataForProfile();
outputToSpreadsheet(results);
} catch(error) {
Browser.msgBox(error.message);
}
}
function getReportDataForProfile() {
var profileId = 'xxxxxxxx'; //firstProfile.getId();
var tableId = 'ga:' + profileId;
var startDate = getLastNdays(14); // 2 weeks (a fortnight) ago.
var endDate = getLastNdays(0); // Today.
var optArgs = {
'dimensions': 'ga:keyword', // Comma separated list of dimensions.
'sort': '-ga:sessions,ga:keyword', // Sort by sessions descending, then keyword.
'segment': 'dynamic::ga:isMobile==Yes', // Process only mobile traffic.
'filters': 'ga:source==google', // Display only google traffic.
'start-index': '1',
'max-results': '250' // Display the first 250 results.
};
// Make a request to the API.
var results = Analytics.Data.Ga.get(
tableId, // Table id (format ga:xxxxxx).
startDate, // Start-date (format yyyy-MM-dd).
endDate, // End-date (format yyyy-MM-dd).
'ga:sessions,ga:pageviews', // Comma seperated list of metrics.
optArgs);
if (results.getRows()) {
return results;
} else {
throw new Error('No views (profiles) found');
}
}
OK, I screwed around with this for a while and then it started working.
My best guess is I copied the property ID from Google Analytics wrong. After going back and recopying it, everything worked well.

How to get statistics of where visitors come from via URL params

There are many QR codes that contains URL of website such as:(it just demos link)
http://www.popupstore.com/index.php?qrcode_type=magazine&location=Singapore
http://www.popupstore.com/index.php?qrcode_type=banner&location=Vietnam
I need a way can summary to know that where customer come from (nearly same as source/channel in Google Analytics):
Type: Mazazine, banner, etc.
Location: Vietnam, Singapore, etc.
Can anyone help me please :)
You could create two Custom Dimensions, each for Type and another for Country
As per your need define the appropriate Scope of the dimension, a Hit level or Session level scope would be appropriate.
You need to push custom dimensions into Google Analytics i.e. additonal JS code in your site.
ga('send', 'pageview', {
'dimension1': 'Magzine',
'dimension2': 'Singapore'
});
How this works
User scans the code and visits the store
Site has a JS code snippet that would get the query parameters from the URL and sets a custom dimension for each parameter
Setting the custom dimension would let Google Analytics know the value of the Type and Country
It is your JS code that tells Google Analytics what value to take for custom dimension. Google Analytics would not know that the value came from the URL.
To get a query parameter value via javascript you can refer to this answer, If you take the function provided there by Jan Turon (head over and give him an upvote of this helps you):
function getJsonFromUrl() {
var query = location.search.substr(1);
var result = {};
query.split("&").forEach(function(part) {
var item = part.split("=");
result[item[0]] = decodeURIComponent(item[1]);
});
return result;
}
You can use this to dynamically set the dimensions based on the url. You first call the function to return an JSON object that has the key/value pairs from the query parameters, then you insert the needed values to set the dimensions:
result = getJsonFromUrl();
ga('send', 'pageview', {
'dimension1': result.qrcode_type,
'dimension2': result.location
});

Resources