Created
November 28, 2019 00:01
-
-
Save lucasjahn/66765046901c55ed52dcaba3610cbee3 to your computer and use it in GitHub Desktop.
Google Tag Manager (GTM) - Google Maps Interaction Tracking
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function () { | |
/** | |
* sends a custom event with a given type to google analytics | |
* | |
* @param {String} type - type of the event to send | |
*/ | |
function sendMapEvent(type) { | |
if(!readCookie('googleMapInteracted')) { | |
dataLayer.push({ | |
'event': 'googlemaps', | |
'eventCategory': 'Google Map', | |
'eventAction': type, | |
'eventLabel': 'Interaction' | |
}); | |
createCookie('googleMapInteracted', 'true', 1) | |
} | |
} | |
/** | |
* bind map events to custom event handler for google analytics events | |
* Please note: Google Map instance must be available under window.map | |
* available map events: https://developers.google.com/maps/documentation/javascript/events | |
*/ | |
function bindMapEvents() { | |
if (window.map) { | |
var map = window.map; | |
map.addListener('dragend', function () { | |
sendMapEvent('dragged'); | |
}); | |
map.addListener('zoom_changed', function () { | |
sendMapEvent('zoomed'); | |
}); | |
map.addListener('maptypeid_changed', function () { | |
sendMapEvent('map type changed'); | |
}); | |
map.addListener('click', function () { | |
sendMapEvent('clicked'); | |
}); | |
map.addListener('rightclick', function () { | |
sendMapEvent('right clicked'); | |
}); | |
map.addListener('dblclick', function () { | |
sendMapEvent('double clicked'); | |
}); | |
} | |
} | |
/** | |
* creates a cookie based on the given name, value and day count | |
* | |
* @param {String} name | |
* @param {String} value | |
* @param {Number} days | |
*/ | |
function createCookie(name, value, days) { | |
if (days) { | |
var date = new Date(); | |
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); | |
var expires = "; expires=" + date.toGMTString(); | |
} else { | |
var expires = ""; | |
} | |
document.cookie = name + "=" + value + expires + "; path=/"; | |
} | |
/** | |
* reads a given cookie by name or return null | |
* | |
* @param {String} name | |
*/ | |
function readCookie(name) { | |
var nameEQ = name + "="; | |
var ca = document.cookie.split(';'); | |
for (var i = 0; i < ca.length; i++) { | |
var c = ca[i]; | |
while (c.charAt(0) == ' ') { | |
c = c.substring(1, c.length); | |
} | |
if (c.indexOf(nameEQ) == 0) { | |
return c.substring(nameEQ.length, c.length); | |
} | |
} | |
return null; | |
} | |
// initially bind all map events | |
bindMapEvents(); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment