-
Notifications
You must be signed in to change notification settings - Fork 595
/
what3words.js
79 lines (76 loc) · 3.8 KB
/
what3words.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
module.exports = function(RED) {
"use strict";
var What3Words = require('geo.what3words');
var what3wordsNode = function(n) {
RED.nodes.createNode(this, n);
this.lang = n.lang || "en";
this.property = n.property||"payload";
var node = this;
//if ( !node.credentials.apikey ) { this.error("No what3words API key set"); }
this.w3w = new What3Words(node.credentials.apikey);
var w1 = /^\*\w{6,31}$/;
var w3 = /^\w+\.\w+\.\w+$/;
this.on("input", function(msg) {
var value = RED.util.getMessageProperty(msg,node.property);
if (value !== undefined) {
if (value.hasOwnProperty("lat") && value.hasOwnProperty("lon")) {
node.w3w.positionToWords({ position:value.lat + "," + value.lon, lang:node.lang })
.then(function(response) {
value = response; // prom.cape.pump
if (!msg.hasOwnProperty("topic") || (msg.topic === "")) { msg.topic = "what3words"; }
RED.util.setMessageProperty(msg,node.property,value);
node.send(msg);
})
.catch(function(err) {
node.warn(err)
});
}
else if (typeof (value) === "string") {
if (value.split(",").length === 2) { // see if it's 2 comma separated words
node.w3w.positionToWords({ position:value, lang:node.lang })
.then(function(response) {
value = response; // prom.cape.pump
if (!msg.hasOwnProperty("topic") || (msg.topic === "")) { msg.topic = "what3words"; }
RED.util.setMessageProperty(msg,node.property,value);
node.send(msg);
})
.catch(function(err) {
node.warn(err);
});
}
else if (value.match(w3)) { // see if it's 3 dot separated words
node.w3w.wordsToPosition({ words:value })
.then(function(response) {
var loc = {};
loc.lat = Number(response.split(",")[0]);
loc.lon = Number(response.split(",")[1]);
RED.util.setMessageProperty(msg,"location",loc);
node.send(msg);
})
.catch(function(err) {
node.warn(err)
});
}
else if (value.match(w1)) { // see if it's a *Oneword
node.w3w.wordsToPosition({ words:value })
.then(function(response) {
var loc = {};
loc.lat = Number(response.split(",")[0]);
loc.lon = Number(response.split(",")[1]);
RED.util.setMessageProperty(msg,"location",loc);
node.send(msg);
})
.catch(function(err) {
node.warn(err);
});
}
else { node.warn("No useable data found. See info."); }
}
else { node.warn("No useable data found. See info."); }
}
});
}
RED.nodes.registerType("what3words", what3wordsNode, {
credentials: { apikey: {type: "password"} }
});
}