Loint
Loint

Reputation: 3938

How to implement geocoding responses using nodejs/javascript?

I'm a newbie in google map api. I'm trying to implement the google maps geocoding api.
Geocoding API on Google Developers

exports.FindByKeyWord = function (req, res, next) {

    var API_KEY = "SOMEDATA";
    var BASE_URL = "https://maps.googleapis.com/maps/api/geocode/json?address=";

    var address = "1600 Amphitheatre Parkway, Mountain View, CA";

    var url = BASE_URL + address + "&key=" + API_KEY;

    var map = new google.maps.Map();
    var geocoder = new google.maps.Geocoder();

    geocoder.geocode(url, function(results, status) {
        if (status === google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });
            res.json(marker);
        } else {
            alert('Geocode was not successful for the following reason: ' + status);
        }
    });
};

I want to response json format, however my function throw an error

google is not define

Can anyone help?

Upvotes: 2

Views: 7641

Answers (1)

Joe Clay
Joe Clay

Reputation: 35787

I think you're getting confused between the Geocoding REST API and the client-side JavaScript API. You're using the latter here, but that's designed to be run in a browser, not on a server, hence why you're getting an error.

Using the REST API is pretty simple in this case - all you have to do is make a HTTP request to the URL you've already created in your example code, and then pass the result through to your server's response. I'd recommend using a library like Request or SuperAgent to simplify this.

Here's an (untested) example, using Request:

// npm install request --save
var request = require("request");

exports.FindByKeyWord = function (req, res, next) {

    var API_KEY = "SOMEDATA";
    var BASE_URL = "https://maps.googleapis.com/maps/api/geocode/json?address=";

    var address = "1600 Amphitheatre Parkway, Mountain View, CA";

    var url = BASE_URL + address + "&key=" + API_KEY;

    request(url, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            res.json(body);
        }
        else {
            // The request failed, handle it
        }
    });
};

Effectively, your server acts as a middleman between your users and the Google API - this can be really handy, as it means you can modify the request before it gets sent off to be geocoded, and allows you to do stuff like caching results (you only get 2,500 free requests a day on the REST API, so this is very important if you expect non-trivial amounts of traffic!).

Upvotes: 10

Related Questions