A.Sharma
A.Sharma

Reputation: 2799

Get Google Maps Geocoding JSON from Express

I've been teaching myself Node.js and Express, and I am trying to return the JSON result from a Google Maps Geocoding API request. I have gotten it to to work using the require module, BUT I am trying to figure out what I did wrong in Express so I have learned it:

Express Attempt: htmlController.js

// FYI: This controller gets called from an app.js file where express() and 
// the mapsAPI is passed as arguments.

var urlencodedParser = bodyParser.urlencoded({extended: false});

module.exports = function(app, mapsAPI){
app.post('/maps', urlencodedParser, function(req,results){
   var lat;
   var long;
   var add = req.body.add;
     app.get('https://maps.googleapis.com/maps/api/geocode/json?address=' + add + '&key=' + mapsAPI, function(req,res){
        lat = res.results.geometry.northeast.lat;
        long = res.results.geometry.northeast.long;
        console.log(lat); // no output
        console.log(lat); // no output
  }, function(){
        console.log(lat); // no output
        console.log(long); // no output
  });
  results.send("Thanks!");
});
}

As you can see, I am trying to log it in different code blocks, but any log inside the API request is not getting shown to the console.

Working Request using the require Module:

app.post('/maps', urlencodedParser, function(req,results){
  var add = req.body.add;
  request({
  url: 'https://maps.googleapis.com/maps/api/geocode/json?address=' + add + '&key=' + mapsAPI,
  json: true
}, function (error, response, body) {
    if (!error && response.statusCode === 200) {
      console.log(body) // Print the json response
    }
  });
  results.send("Thanks!");
});

Upvotes: 0

Views: 1922

Answers (1)

Ikrum Hossain
Ikrum Hossain

Reputation: 210

If I understand you correctly, you are trying to get data from maps api by using app.get()

app.get('https://maps.googleapis.com/maps/api/geocode/json?address=' + add + '&key=' + mapsAPI, function(req,res){}

But app.get() function is used for your app route only, not to fetch remote data. same for router.get()

// app.get(appRoute, middlewareORhandler)
app.get('/myOwnApp/api/users/12/', function(res,res,next)){
    // your code here
    res.status(200).send("return your response here");
}

to make a remote request you can use built-in httpmodule. request and superagent are great and easy to make remote requests

to install those module:

npm install request --save
var request = require('request');

npm install superagent --save
var request = require('superagent');

see more at : https://www.npmjs.com/package/request

Upvotes: 1

Related Questions