forked from stamen/node-geocoder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
83 lines (66 loc) · 2.43 KB
/
index.js
File metadata and controls
83 lines (66 loc) · 2.43 KB
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
80
81
82
83
"use strict";
if (!process.env.CONSUMER_KEY || !process.env.CONSUMER_SECRET) {
console.error("Please provide CONSUMER_KEY and CONSUMER_SECRET");
process.exit(1);
}
var BossGeoClient = require("bossgeo").BossGeoClient,
cors = require("cors"),
geo = new BossGeoClient(process.env.CONSUMER_KEY,
process.env.CONSUMER_SECRET),
express = require("express"),
app = express();
// radius of the earth in meters
var RADIUS = 40075016.69;
var π = Math.PI;
app.configure(function() {
app.use(express.logger());
app.use(express.compress());
app.use(cors());
});
app.get("/", function(req, res) {
var smallEdge = Math.min(req.query.w || 1000, req.query.h || 768);
if (!req.query.q) {
return res.send(404);
}
// Current (v4.13.3) express js code instantiates the req object without
// the Object prototype, while the npm "bossgeo" library calls query.hasOwnProperty.
// Construct a normal query Object from req.query for use with the bossgeo placefinder method.
var query = {}
for (var propName in req.query) {
if (Object.prototype.hasOwnProperty.call(req.query, propName)) {
query[propName] = req.query[propName];
}
}
geo.placefinder(query, function(err, rsp) {
if (err) {
console.log('-----Error-----: ', rsp);
console.warn(err);
return res.send(500);
}
console.log(rsp);
var results = (rsp.results || []).map(function(x) {
var radius = +x.radius;
var zoom = -Math.round(Math.log((radius) / (RADIUS / Math.cos(+x.latitude * π / 180)) / Math.log(smallEdge)));
x.name = [x.city, x.state, x.country].filter(function(x) { return !!x; }).join(", "),
x.latitude = +x.latitude,
x.longitude = +x.longitude,
x.state = x.statecode,
x.zoom = zoom
return x;
});
res.jsonp(results);
});
});
app.get("/crossdomain.xml", onCrossDomainHandler)
function onCrossDomainHandler(req, res) {
var xml = '<?xml version="1.0"?>\n<!DOCTYPE cross-domain-policy SYSTEM' +
' "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">\n<cross-domain-policy>\n';
xml += '<allow-access-from domain="*" to-ports="*"/>\n';
xml += '</cross-domain-policy>\n';
req.setEncoding('utf8');
res.writeHead( 200, {'Content-Type': 'text/xml'} );
res.end( xml );
}
app.listen(process.env.PORT || 8080, function() {
console.log("Listening at http://%s:%d/", this.address().address, this.address().port);
});