Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
## v3.1.2

- Enable inaction event logging

### v3.1.1

- [bug] Ensures proximity is passed to client [#180](https://github.com/mapbox/mapbox-gl-geocoder/pull/180)
Expand Down
2 changes: 2 additions & 0 deletions debug/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@
var mapboxgl = require('mapbox-gl');
var insertCss = require('insert-css');
var fs = require('fs');

mapboxgl.accessToken = window.localStorage.getItem('MapboxAccessToken');


var meta = document.createElement('meta');
meta.name = 'viewport';
meta.content = 'initial-scale=1,maximum-scale=1,user-scalable=no';
Expand Down
220 changes: 220 additions & 0 deletions lib/events.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
'use strict';

var request = require('request');
var crypto = require('crypto');

/**
* Construct a new mapbox event client to send interaction events to the mapbox event service
* @param {Object} options options with which to create the service
* @param {String} options.accessToken the mapbox access token to make requests
* @private
*/
function MapboxEventManager(options){
this.origin = options.origin || 'https://api.mapbox.com';
this.endpoint = this.origin + '/events/v2';
this.access_token = options.accessToken;
this.version = '0.0.1'
this.sessionID = this.generateSessionID();
this.userAgent = this.getUserAgent();
// parse global options to be sent with each request
this.countries = (options.countries) ? options.countries.split(",") : null;
this.types = (options.types) ? options.types.split(",") : null;
this.bbox = (options.bbox) ? options.bbox : null;
this.language = (options.language) ? options.language.split(",") : null;
this.limit = (options.limit) ? +options.limit : null;
this.locale = navigator.language || null;
this.enableEventLogging = this.shouldEnableLogging(options);
// keep some state to deduplicate requests if necessary
this.lastSentInput = "";
this.lastSentIndex = 0;
}

MapboxEventManager.prototype = {

/**
* Send a search.select event to the mapbox events service
* This event marks the array index of the item selected by the user out of the array of possible options
* @private
* @param {Object} selected the geojson feature selected by the user
* @param {Object} geocoder a mapbox-gl-geocoder instance
* @param {Function} callback a callback function to invoke once the event has been sent (optional)
* @returns {Promise}
*/
select: function(selected, geocoder, callback){
var resultIndex = this.getSelectedIndex(selected, geocoder);
var payload = this.getEventPayload('search.select', geocoder);
payload.resultIndex = resultIndex;
if (resultIndex === this.lastSentIndex && payload.queryString === this.lastSentInput) {
// don't log duplicate events if the user re-selected the same feature on the same search
if (callback) return callback();
}
this.lastSentIndex = resultIndex;
this.lastSentInput = payload.queryString;
return this.send(payload, callback)
},

/**
* Send a search-start event to the mapbox events service
* This turnstile event marks when a user starts a new search
* @private
* @param {Object} geocoder a mapbox-gl-geocoder instance
* @param {Function} callback
* @returns {Promise}
*/
start: function(geocoder, callback){
var payload = this.getEventPayload('search.start', geocoder);
return this.send(payload, callback);
},

/**
* Send an event to the events service
*
* The event is skipped if the instance is not enabled to send logging events
*
* @private
* @param {Object} payload the http POST body of the event
* @returns {Promise}
*/
send: function(payload, callback){
if (!callback) callback = function(){return};
if (!this.enableEventLogging){
return callback();
}
var options = this.getRequestOptions(payload);
this.request(options, function(err,res){
if (err) return this.handleError(err, callback);
if (res.statusCode != 204) return this.handleError(res, callback);
if (callback) return callback();
})
},
/**
* Get http request options
* @private
* @param {*} payload
*/
getRequestOptions: function(payload){
var options = {
// events must be sent with POST
method: "POST",
url: this.endpoint,
headers:{
'Content-Type': 'application/json'
},
qs: {
access_token: this.access_token
},
body:JSON.stringify([payload]) //events are arrays
}
return options
},

/**
* Get the event payload to send to the events service
* Most payload properties are shared across all events
* @private
* @param {String} event the name of the event to send to the events service. Valid options are 'search.start', 'search.select', 'search.feedback'.
* @param {Object} geocoder a mapbox-gl-geocoder instance
* @returns {Object} an event payload
*/
getEventPayload: function(event, geocoder){
var proximity;
if (!geocoder.options.proximity) proximity = null;
else proximity = [geocoder.options.proximity.longitude, geocoder.options.proximity.latitude ];

var zoom = (geocoder._map) ? geocoder._map.getZoom() : null;
return {
event: event,
created: +new Date(),
sessionIdentifier: this.sessionID,
country: this.countries,
userAgent: this.userAgent,
language: this.language,
bbox: this.bbox,
types: this.types,
endpoint: 'mapbox.places',
// fuzzyMatch: search.fuzzy, //todo --> add to plugin
proximity: proximity,
limit: geocoder.options.limit,
// routing: search.routing, //todo --> add to plugin
queryString: geocoder.inputString,
mapZoom: zoom,
keyboardLocale: this.locale
}
},

/**
* Wraps the request function for easier testing
* Make an http request and invoke a callback
* @private
* @param {Object} opts options describing the http request to be made
* @param {Function} callback the callback to invoke when the http request is completed
*/
request: function(opts, callback){
request(opts, function(err, res){
return callback(err, res);
})
},

/**
* Handle an error that occurred while making a request
* @param {Object} err an error instance to log
* @private
*/
handleError: function(err, callback){
if (callback) return callback(err);
},

/**
* Generate a session ID to be returned with all of the searches made by this geocoder instance
* ID is random and cannot be tracked across sessions
* @private
*/
generateSessionID: function(){
var sha = crypto.createHash('sha256');
sha.update(Math.random().toString());
return sha.digest('hex')
},

/**
* Get a user agent string to send with the request to the events service
* @private
*/
getUserAgent: function(){
return 'mapbox-gl-geocoder.' + this.version + "." + navigator.userAgent;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When I test this locally with yarn run start it reports "undefined" here. Not sure if that's intended or not?

},

/**
* Get the 0-based numeric index of the item that the user selected out of the list of options
* @private
* @param {Object} selected the geojson feature selected by the user
* @param {Object} geocoder a Mapbox-GL-Geocoder instance
* @returns {Number} the index of the selected result
*/
getSelectedIndex: function(selected, geocoder){
var results = geocoder._typeahead.data;
var selectedID = selected.id;
var resultIDs = results.map(function (feature){
return feature.id;
});
var selectedIdx = resultIDs.indexOf(selectedID);
return selectedIdx;
},

/**
* Check whether events should be logged
* Clients using a localGeocoder or an origin other than mapbox should not have events logged
* @private
*/
shouldEnableLogging: function(options){
if (!this.origin.includes('api.mapbox.com')) return false;
// hard to make sense of events when a local instance is suplementing results from origin
if (options.localGeocoder) return false;
// hard to make sense of events when a custom filter is in use
if (options.filter) return false;
return true;
}
}



module.exports = MapboxEventManager;
20 changes: 17 additions & 3 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ var EventEmitter = require('events').EventEmitter;
var exceptions = require('./exceptions');
var MapboxClient = require('@mapbox/mapbox-sdk');
var mbxGeocoder = require('@mapbox/mapbox-sdk/services/geocoding');
var MapboxEventManager = require('./events');
var geocoderService;

/**
Expand Down Expand Up @@ -49,6 +50,8 @@ var geocoderService;
function MapboxGeocoder(options) {
this._eventEmitter = new EventEmitter();
this.options = extend({}, this.options, options);
this.inputString = '';
this.fresh = true;
}

MapboxGeocoder.prototype = {
Expand All @@ -59,7 +62,8 @@ MapboxGeocoder.prototype = {
trackProximity: false,
minLength: 2,
reverseGeocode: false,
limit: 5
limit: 5,
origin: 'https://api.mapbox.com'
},

onAdd: function(map) {
Expand All @@ -68,10 +72,12 @@ MapboxGeocoder.prototype = {
geocoderService = mbxGeocoder(
MapboxClient({
accessToken: this.options.accessToken,
origin: this.options.origin || 'https://api.mapbox.com'
origin: this.options.origin
})
);

this.eventManager = new MapboxEventManager(this.options);

this._onChange = this._onChange.bind(this);
this._onKeyDown = this._onKeyDown.bind(this);
this._onQueryResult = this._onQueryResult.bind(this);
Expand Down Expand Up @@ -144,6 +150,7 @@ MapboxGeocoder.prototype = {
? e.target.shadowRoot.activeElement
: e.target;
if (!target.value) {
this.fresh = true;
return (this._clearEl.style.display = 'none');
}

Expand Down Expand Up @@ -180,13 +187,14 @@ MapboxGeocoder.prototype = {
}
}
this._eventEmitter.emit('result', { result: selected });
this.eventManager.select(selected, this);
}
},

_geocode: function(searchInput) {
this._loadingEl.style.display = 'block';
this._eventEmitter.emit('loading', { query: searchInput });

this.inputString = searchInput;
// Possible config proprerties to pass to client
var keys = [
'bbox',
Expand Down Expand Up @@ -272,6 +280,10 @@ MapboxGeocoder.prototype = {
}

res.config = config;
if (this.fresh){
this.eventManager.start(this);
this.fresh = false;
}
this._eventEmitter.emit('results', res);
this._typeahead.update(res.features);
}.bind(this)
Expand Down Expand Up @@ -307,6 +319,8 @@ MapboxGeocoder.prototype = {
this._inputEl.focus();
this._clearEl.style.display = 'none';
this._eventEmitter.emit('clear');
// reset the turnstile event
this.fresh = true;
},

_onQueryResult: function(response) {
Expand Down
Loading