using the new geocoder

This commit is contained in:
Martin Donnelly 2018-11-04 12:03:30 +00:00
parent 9e69e6942f
commit 7f7c1f1734
5 changed files with 107 additions and 89 deletions

16
package-lock.json generated
View File

@ -52,7 +52,7 @@
},
"@sinonjs/formatio": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/@sinonjs/formatio/-/formatio-2.0.0.tgz",
"resolved": "http://registry.npmjs.org/@sinonjs/formatio/-/formatio-2.0.0.tgz",
"integrity": "sha512-ls6CAMA6/5gG+O/IdsBcblvnd8qcO/l1TYoNeAzp3wcISOxlPXQEus0mLcdwazEkWjaBdaJ3TaxmNgCLWwvWzg==",
"dev": true,
"requires": {
@ -9924,11 +9924,20 @@
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/request-promise-core/-/request-promise-core-1.1.1.tgz",
"integrity": "sha1-Pu4AssWqgyOc+wTFcA2jb4HNCLY=",
"dev": true,
"requires": {
"lodash": "^4.13.1"
}
},
"request-promise-native": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/request-promise-native/-/request-promise-native-1.0.5.tgz",
"integrity": "sha1-UoF3D2jgyXGeUWP9P6tIIhX0/aU=",
"requires": {
"request-promise-core": "1.1.1",
"stealthy-require": "^1.1.0",
"tough-cookie": ">=2.3.3"
}
},
"requestretry": {
"version": "1.13.0",
"resolved": "https://registry.npmjs.org/requestretry/-/requestretry-1.13.0.tgz",
@ -10807,8 +10816,7 @@
"stealthy-require": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/stealthy-require/-/stealthy-require-1.1.1.tgz",
"integrity": "sha1-NbCYdbT/SfJqd35QmzCQoyJr8ks=",
"dev": true
"integrity": "sha1-NbCYdbT/SfJqd35QmzCQoyJr8ks="
},
"stream-browserify": {
"version": "2.0.1",

View File

@ -44,6 +44,7 @@
"node-foursquare-venues": "^1.1.0",
"openweather-apis": "^3.3.5",
"request-json": "^0.6.3",
"request-promise-native": "^1.0.5",
"strict-uri-encode": "^2.0.0",
"string": "^3.3.3",
"sugar": "^2.0.4",

View File

@ -32,7 +32,10 @@ function formatResult (result) {
'streetNumber': result.components.house_number,
'countryCode': result.components.country_code,
'county': result.components.county,
'suburb': result.components.suburb || '',
'suburb': result.components.suburb,
'neighbourhood' : result.components.neighbourhood,
'village' : result.components.village,
'formatted' : result.formatted,
'extra': {
'flag' : result.annotations.flag,
'confidence': confidence,
@ -44,11 +47,11 @@ function formatResult (result) {
}
function reduceOpencage(result) {
var results = [];
logger.debug(JSON.stringify(result));
const results = [];
if (result && result.results instanceof Array)
for (var i = 0; i < result.results.length; i++)
for (let i = 0; i < result.results.length; i++)
results.push(formatResult(result.results[i]));
return results;

View File

@ -11,7 +11,7 @@
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
const CACHE_VERSION = { 'version': '0.0.934' };
const CACHE_VERSION = { 'version': '0.0.955' };
const PRECACHE = `jubileeData-${CACHE_VERSION.version}`;
const RUNTIME = 'runtime';

View File

@ -2,10 +2,10 @@ const _ = require('underscore');
const Backbone = require('backbone');
const geolocation = require('geolocation');
const TimeFormat = require('hh-mm-ss');
const request = require('request');
const { distance } = require('./libs/utils');
const NodeGeocoder = require('node-geocoder');
// const locationData = require('./portGlasgow-Aldi-2018-03-09.json');
const LocationModel = Backbone.Model.extend({
@ -13,7 +13,7 @@ const LocationModel = Backbone.Model.extend({
// defaults go here - "children" may be contained here
},
'tick': function() {
'tick': function () {
const p = locationData[this.pos];
const now = new Date();
@ -29,7 +29,7 @@ const LocationModel = Backbone.Model.extend({
p.time
);
},
'initialize': function() {
'initialize': function () {
// this.listenTo(this, 'change sync reset', this.onChange);
// https://opencagedata.com/dashboard
@ -49,12 +49,12 @@ const LocationModel = Backbone.Model.extend({
geolocation.options = geoOptions;
geolocation.on('error', function(err) {
geolocation.on('error', function (err) {
console.warn('Geolocation error');
console.error(err);
});
geolocation.on('change', function( position) {
geolocation.on('change', function (position) {
console.log('Location update');
const location = { 'latitude': position.coords.latitude, 'longitude': position.coords.longitude, 'timestamp': position.timestamp };
@ -64,10 +64,10 @@ const LocationModel = Backbone.Model.extend({
this.processPosition(location);
this.throttler = now.getTime() + 1000;
}
else
else
console.log('Throttling location update...');
// this.set('location', location);
// this.set('location', location);
}.bind(this));
this.watcher = geolocation.createWatcher();
@ -75,66 +75,64 @@ const LocationModel = Backbone.Model.extend({
this.listenTo(this, 'change:location', this.onChange);
// this.tick();
},
'onChange': function() {
'onChange': function () {
console.log('>> Location updated');
console.log(JSON.stringify(this.get('location')));
},
'processPosition': function(pos) {
'processPosition': function (pos) {
console.log('processPosition');
const { latitude, longitude, timestamp } = pos;
let { latitude, longitude, timestamp } = pos;
latitude = Number.parseFloat(latitude).toFixed(6);
longitude = Number.parseFloat(longitude).toFixed(6);
// const current = this.get('location');
const current = this.toJSON();
// console.log('># current', current);
/*const options = {
'provider': 'google',
// Optional depending on the providers
'httpAdapter': 'https', // Default
'apiKey': 'AIzaSyA7oGP6QS28tTwtT6UzA7hzh0b3MWwMYB8', // for Mapquest, OpenCage, Google Premier
'formatter': null // 'gpx', 'string', ...
};*/
// opencage 893ab539eca84b5ca7a54cb03ef23443
const options = {
'provider': 'opencage',
// Optional depending on the providers
'httpAdapter': 'https', // Default
'apiKey': '893ab539eca84b5ca7a54cb03ef23443', // for Mapquest, OpenCage, Google Premier
'formatter': null // 'gpx', 'string', ...
};
const myCoords = { 'home': {
'lat':51.490002, 'long':-0.140245
},
'work':{
'lat':51.5084707, 'long':-0.068798
} };
const myCoords = {
'home': {
'lat': 51.490002, 'long': -0.140245
},
'work': {
'lat': 51.508471, 'long': -0.068798
}
};
// rawburn house 51.490002, -0.140245
// thomas more 51.5084707,-0.068798
const geocoder = NodeGeocoder(options);
// 55.872407, -3.549003
const homeDistance = distance(myCoords.home.lat, myCoords.home.long, latitude, longitude);
const workDistance = distance(myCoords.work.lat, myCoords.work.long, latitude, longitude);
const atHome = (homeDistance < 0.10);
const atWork = (workDistance < 0.10);
const atHomeOrWork = (atHome || atWork);
const latlong = { 'lat':latitude, 'lon':longitude };
const latlong = { 'lat': latitude, 'lon': longitude };
const ll = `${latitude},${longitude}`;
const llFixed = `${Number.parseFloat(latitude).toFixed(3)},${Number.parseFloat(longitude).toFixed(3)}`;
const llSix = `${Number.parseFloat(latitude).toFixed(6)},${Number.parseFloat(longitude).toFixed(6)}`;
const llShort = `${Number.parseFloat(latitude).toFixed(1)},${Number.parseFloat(longitude).toFixed(1)}`;
const moving = true;
const newLocation = { homeDistance, workDistance, latitude, longitude, atHome, atWork, atHomeOrWork, timestamp, ll, llFixed, llSix, llShort, moving, latlong, 'city' : '', 'cityCC':'' };
const newLocation = {
homeDistance,
workDistance,
latitude,
longitude,
atHome,
atWork,
atHomeOrWork,
timestamp,
ll,
llFixed,
llSix,
llShort,
moving,
latlong,
'city': '',
'cityCC': ''
};
console.log('homeDistance', homeDistance, 'workDistance:', workDistance);
// console.log('>> NewLocation', JSON.stringify(newLocation));
@ -142,23 +140,28 @@ const LocationModel = Backbone.Model.extend({
if (!_.has(current, 'atHomeOrWork')) {
console.info('>> Location:geocoder request');
geocoder.reverse(latlong)
.then(function(res) {
console.log(JSON.stringify(res));
newLocation.city = res[0].extra.neighborhood || res[0].city;
newLocation.cityCC = `${res[0].city},${res[0].countryCode}`;
newLocation.address = res[0].formattedAddress;
// this.set('location', newLocation);
newLocation.lastGeocode = { 'lat':latitude, 'lng':longitude, 'timestamp':timestamp };
this.set( newLocation);
// this.set('moving', moving);
// this.set('lastGeocode', { 'lat':latitude, 'lng':longitude, 'timestamp':timestamp });
// console.log('### location', this);
}.bind(this))
.catch(function(err) {
request({
'url': `${window.loc}/geocode`,
'method': 'GET',
'qs': {
'll': ll
},
'json': true
}, function(err, res, body) {
if (err)
console.error(err);
this.set('location', newLocation);
});
else {
console.log('New geocode', res);
const body = res.body;
const __city = body.neighborhood || body.village || body.suburb || body.city || body.county;
newLocation.city = __city;
newLocation.cityCC = `${__city},${body.countryCode}`;
newLocation.address = body.formatted;
newLocation.lastGeocode = { 'lat': latitude, 'lng': longitude, 'timestamp': timestamp };
this.set(newLocation);
}
}.bind(this));
}
else {
newLocation.city = current.city;
@ -176,34 +179,37 @@ const LocationModel = Backbone.Model.extend({
// console.log(`(currentTime:${currentTime}, timestamp:${timestamp}, lastGeocode.timestamp:${lastGeocode.timestamp})`);
// console.log('(currentTime - current.timestamp > 900000) ', (currentTime - current.timestamp > 900000));
// if ((distanceFromLast > 0.5 && distanceFromLast < 2.0) || (timestamp - current.timestamp > 900000)) {
if (((distanceFromLast > 0.80 && distanceFromLast < 2.0) && ( currentSince > 120000)) || ((currentSince > 900000) && (sinceLastGeocode < 1.8e+6))) {
if (((distanceFromLast > 0.80 && distanceFromLast < 2.0) && (currentSince > 120000)) || ((currentSince > 900000) && (sinceLastGeocode < 1.8e+6))) {
// dont bother re geocoding
console.log('Slightly moved from previous');
// this.set('location', newLocation);
// this.set('moving', moving);
this.set( newLocation);
this.set(newLocation);
}
else if (((distanceFromLastGeocode >= 2.0) && (sinceLastGeocode > 120000)) || (sinceLastGeocode >= 1.8e+6) ) {
else if (((distanceFromLastGeocode >= 2.0) && (sinceLastGeocode > 120000)) || (sinceLastGeocode >= 1.8e+6)) {
console.log('>> Moved from previous', sinceLastGeocode, (sinceLastGeocode >= 1.8e+6));
console.info('>> Location:geocoder request');
geocoder.reverse(latlong)
.then(function(res) {
console.log('>> location res', JSON.stringify(res));
newLocation.city = res[0].extra.neighborhood || res[0].city;
newLocation.cityCC = `${res[0].city},${res[0].countryCode}`;
newLocation.address = res[0].formattedAddress;
console.log('!!! Setting location...');
// this.set('location', newLocation);
// this.set('lastGeocode', { 'lat':latitude, 'lng':longitude, 'timestamp':timestamp });
// this.set('moving', moving);
newLocation.lastGeocode = { 'lat':latitude, 'lng':longitude, 'timestamp':timestamp };
this.set( newLocation);
console.log(this);
}.bind(this))
.catch(function(err) {
request({
'url': `${window.loc}/geocode`,
'method': 'GET',
'qs': {
'll': ll
},
'json': true
}, function(err, res, body) {
if (err)
console.error(err);
this.set( newLocation);
});
else {
console.log('New geocode', res);
const body = res.body;
const __city = body.neighborhood || body.village || body.suburb || body.city || body.county;
newLocation.city = __city;
newLocation.cityCC = `${__city},${body.countryCode}`;
newLocation.address = body.formatted;
newLocation.lastGeocode = { 'lat': latitude, 'lng': longitude, 'timestamp': timestamp };
this.set(newLocation);
}
}.bind(this));
}
}
@ -228,12 +234,12 @@ const LocationModel = Backbone.Model.extend({
});
const LocationView = Backbone.View.extend({
'initialize' : function(options) {
'initialize': function (options) {
this.model.bind('change', this.render, this);
}, 'template': _.template(`
<div class="">Moving:<%=moving%></div>
`),
'render': function() {
'render': function () {
this.$el.html(this.template(this.model.attributes));
console.log('>> location attributes', this.model.attributes);