-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
58 lines (47 loc) · 1.41 KB
/
index.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
'use strict'
var qs = require('querystring')
var https = require('https')
var once = require('once')
var processBody = function (body, cb) {
if (body.status !== 'OK') return cb()
cb(null, {
lat: body.location.lat,
lng: body.location.lng,
accuracy: body.accuracy
})
}
module.exports = function (towers, cb) {
cb = once(cb)
var wifi = (towers || [])
.slice(0, 20) // if the URL is too long, Google will repond with 411
.map(function (tower) {
var ss = 'signal' in tower ? tower.signal : tower.signal_level
return qs.escape('mac:' + tower.mac + '|ssid:' + tower.ssid + '|ss:' + ss)
})
.join('&wifi=')
if (wifi) wifi = '&wifi=' + wifi
var opts = {
hostname: 'maps.googleapis.com',
method: 'POST',
path: '/maps/api/browserlocation/json?browser=firefox&sensor=true' + wifi
}
var req = https.request(opts, function (res) {
var buffers = []
res.on('data', buffers.push.bind(buffers))
res.on('end', function () {
if (res.statusCode >= 300) return cb(new Error('Geocoding service returned unexpected status code: ' + res.statusCode))
var body = Buffer.concat(buffers)
try {
body = JSON.parse(body)
} catch (e) {
return cb(e)
}
processBody(body, cb)
})
})
req.on('error', cb)
req.on('close', function () {
cb(new Error('Connection to geocoding service closed unexpectedly'))
})
req.end()
}