Skip to content

Instantly share code, notes, and snippets.

@davidfloyd91
Last active May 31, 2019 21:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidfloyd91/e7a57dfc5882096ffc971d2917ceadd5 to your computer and use it in GitHub Desktop.
Save davidfloyd91/e7a57dfc5882096ffc971d2917ceadd5 to your computer and use it in GitHub Desktop.
Get geographic location by querying Google's Geolocation API with Node (Express). Accompanies this brief explainer: https://davidfloyd91.github.io/google-geolocation-api-node-express/
// https://davidfloyd91.github.io/google-geolocation-api-node-express/
const express = require('express');
const https = require('https');
const app = express();
const port = 3000;
let lat, lng;
const googleKey = process.env.GOOGLE_API_KEY;
// $ curl -X POST -H 'Content-Type: application/json' https://www.googleapis.com/geolocation/v1/geolocate?key=$GOOGLE_API_KEY
const googleOptions = {
hostname: 'www.googleapis.com',
path: `/geolocation/v1/geolocate?key=${googleKey}`,
method: 'POST',
headers: { 'Content-Type': 'application/json' }
};
app.get('/', (req, res) => {
res.send('Hello World!')
});
// $ curl -X GET -H 'Content-Type: application/json' http://localhost:3000/location
app.get('/location', (req, res) => {
let data = '';
const request = https.request(googleOptions, (response) => {
console.log(`STATUS: ${response.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(response.headers)}`);
response.setEncoding('utf8');
response.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
data += chunk;
});
response.on('end', () => {
console.log('No more data in response.');
let coords = JSON.parse(data);
lat = coords.location.lat;
lng = coords.location.lng;
res.send(coords);
});
});
request.on('error', (e) => {
console.error(`problem with request: ${e.message}`);
});
request.end();
});
app.listen(port, () => {
console.log(`Listening on port ${port}!`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment