Repository: wyattdanger/geocoder Branch: master Commit: 135df34eba20 Files: 11 Total size: 19.7 KB Directory structure: gitextract_hi2tzpv9/ ├── .gitignore ├── LICENSE ├── README.markdown ├── index.js ├── package.json ├── providers/ │ ├── geonames.js │ ├── google.js │ └── yahoo.js └── test/ ├── geocoder-geonames-test.js ├── geocoder-google-test.js └── geocoder-yahoo.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ .*.sw* node_modules scrap.js ================================================ FILE: LICENSE ================================================ Copyright (c) 2011 Stephen Wyatt Bush Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.markdown ================================================ # Geocoder ###Installation: npm install geocoder ### Usage You can pass a string representation of a location and a callback function to `geocoder.geocode`. It will accept anything that Google will accept: cities, streets, countries, etc. ###Example: ```javascript var geocoder = require('geocoder'); // Geocoding geocoder.geocode("Atlanta, GA", function ( err, data ) { // do something with data }); // Reverse Geocoding geocoder.reverseGeocode( 33.7489, -84.3789, function ( err, data ) { // do something with data }); // Setting sensor to true geocoder.reverseGeocode( 33.7489, -84.3789, function ( err, data ) { // do something with data }, { sensor: true }); // Setting language to German geocoder.reverseGeocode( 33.7489, -84.3789, function ( err, data ) { // do something with data }, { language: 'de' }); // Selecting another provider to do reverse geocoding // Currently only geonames and yahoo placefinder are supported geocoder.selectProvider("geonames",{"username":"demo"}); // Output will be roughly in the same format as Google's geocoder.reverseGeocode( 33.7489, -84.3789, function ( err, data ) { // do something with data }); // see http://developer.yahoo.com/geo/placefinder/guide/index.html geocoder.selectProvider("yahoo",{"appid":"xxx"}); // Output will be roughly in the same format as Google's geocoder.reverseGeocode( 33.7489, -84.3789, function ( err, data ) { // do something with data }); ``` Results will look like standard [Google JSON Output](http://code.google.com/apis/maps/documentation/geocoding/#JSON) You can pass in an optional options hash as a last argument, useful for setting sensor to true (it defaults to false) and the language (default is empty which means that google geocoder will guess it by geo ip data). For details see the [Google Geocoding API Docs](https://developers.google.com/maps/documentation/javascript/geocoding) ###Testing: `nodeunit test` ## Roadmap - Complete Test Suite - Better options handling ## Further Reading - [Blog post](http://blog.stephenwyattbush.com/2011/07/16/geocoding-with-nodejs/) ================================================ FILE: index.js ================================================ /** * Geocoder */ /** * Module Dependencies */ /** * Version */ var version = '0.2.3'; /** * Geocoder */ function Geocoder () { this.selectProvider("google"); }; /** * Geocoder prototype */ Geocoder.prototype = { /** * Selects a webservice provider * * @param {String} name, required * @param {Object} opts, optional * @api public */ selectProvider: function ( name, opts ) { if ( ! name ) { return cbk( new Error( "Geocoder.selectProvider requires a name.") ); } this.provider = name; this.providerOpts = opts || {}; this.providerObj = require("./providers/"+name); }, /** * Request geocoordinates of given `loc` from Google * * @param {String} loc, required * @param {Function} cbk, required * @param {Object} opts, optional * @api public */ geocode: function ( loc, cbk, opts ) { if ( ! loc ) { return cbk( new Error( "Geocoder.geocode requires a location.") ); } return this.providerObj.geocode(this.providerOpts, loc, cbk, opts); }, reverseGeocode: function ( lat, lng, cbk, opts ) { if ( !lat || !lng ) { return cbk( new Error( "Geocoder.reverseGeocode requires a latitude and longitude." ) ); } return this.providerObj.reverseGeocode(this.providerOpts, lat, lng, cbk, opts ); }, /** * Return Geocoder version * * @api public */ version: version }; /** * Export */ module.exports = new Geocoder(); ================================================ FILE: package.json ================================================ { "name": "geocoder", "description": "Geocoding through Google's Developer API", "version": "0.2.3", "main": "./index.js", "description": "node wrapper around google's geocoder api", "author": "Stephen Wyatt Bush ", "repository" : "git://github.com/wyattdanger/geocoder", "homepage" : "https://github.com/wyattdanger/geocoder", "keywords" : [ "google", "geocode", "geonames", "reverse geocode" ], "license": { "type": "Apachev2", "url": "http://www.apache.org/licenses/LICENSE-2.0" }, "dependencies" : { "underscore" : "1.3.3", "request":"^2.75.0" }, "optionalDependencies": { "xml2js": "0.2.0" } } ================================================ FILE: providers/geonames.js ================================================ // xml2js is optional because only needed for geonames support var xml2js = require("xml2js"); var request = require("request"); var _ = require('underscore'); exports.geocode = function ( providerOpts, loc, cbk, opts ) { var options = _.extend({q: loc, maxRows: 10, username:providerOpts.username||"demo" }, opts || {}); request({ uri:"http://api.geonames.org/searchJSON", qs:options }, function(err,resp,body) { if (err) return cbk(err); var result; try { result = JSON.parse(body); } catch (err) { cbk(err); return; } cbk(null,result); }); }; exports.reverseGeocode = function ( providerOpts, lat, lng, cbk, opts ) { var options = _.extend({lat:lat, lng:lng, username:providerOpts.username||"demo" }, opts || {}); request({ uri:"http://api.geonames.org/extendedFindNearby", qs:options }, function(err,resp,body) { if (err) return cbk(err); var parser = new xml2js.Parser(); parser.parseString(body, function (err, result) { if (err) return cbk(err); // Transform geonames' structure into something that looks like Google's JSON outpu // https://developers.google.com/maps/documentation/geocoding/#JSON var googlejson = { "status":"OK", "results":[ { "address_components":[], "formatted_address":"", "geometry":{ "location":{ "lat":lat, "lng":lng } } } ] }; if (result.geonames.address) { var a = result.geonames.address[0]; if (a.streetNumber && typeof a.streetNumber[0]=="string") googlejson.results[0].address_components.push({ "long_name":a.streetNumber[0], "short_name":a.streetNumber[0], "types":["street_number"] }); if (a.street && typeof a.street[0]=="string") googlejson.results[0].address_components.push({ "long_name":a.street[0], "short_name":a.street[0], "types":["route"] }); if (a.placename && typeof a.placename[0]=="string") googlejson.results[0].address_components.push({ "long_name":a.placename[0], "short_name":a.placename[0], "types":["locality", "political"] }); if (a.adminName1 && typeof a.adminName1[0]=="string") googlejson.results[0].address_components.push({ "long_name":a.adminName1[0], "short_name":a.adminCode1[0], "types":[ "administrative_area_level_1", "political" ] }); if (a.adminName2 && typeof a.adminName2[0]=="string") googlejson.results[0].address_components.push({ "long_name":a.adminName2[0], "short_name":a.adminCode2[0], "types":[ "administrative_area_level_2", "political" ] }); if (a.countryCode && typeof a.countryCode[0]=="string") googlejson.results[0].address_components.push({ "long_name":a.countryCode[0]=="US"?"United States":"", "short_name":a.countryCode[0], "types":[ "country" ] }); if (a.lat && typeof a.lat[0]=="string") googlejson.results[0].geometry.location = { "lat":parseFloat(a.lat[0]), "lng":parseFloat(a.lng[0]) } } if (result.geonames.geoname) { // http://www.geonames.org/export/codes.html // https://developers.google.com/maps/documentation/geocoding/#Types var fcode2google = { "ADM1":[ "administrative_area_level_1", "political" ], "ADM2":[ "administrative_area_level_2", "political" ], "ADM3":[ "administrative_area_level_3", "political" ], "ADMD":[ "political"], "PPL" :[ "locality"] }; result.geonames.geoname.forEach(function(geoname) { // Push only recognized types to results if (geoname.fcode[0]=="PCLI") { googlejson.results[0].address_components.push({ "long_name":geoname.name[0], "short_name":geoname.countryCode[0], "types":[ "country", "political"] }); } else if (fcode2google[geoname.fcode[0]]) { googlejson.results[0].address_components.push({ "long_name":geoname.toponymName[0], "short_name":geoname.name[0], "types":fcode2google[geoname.fcode[0]] }); } }); } // Make a formatted address as well as we can var shortNames = {}; googlejson.results[0].address_components.forEach(function(c) { if (c.types[0]=="country") return shortNames.country = c.long_name || c.short_name; shortNames[c.types[0]] = c.short_name; }); var formatted = []; if (shortNames.street_number || shortNames.route) { formatted.push((shortNames.street_number?shortNames.street_number+" ":"")+shortNames.route); } if (shortNames.locality) { formatted.push(shortNames.locality); } if (shortNames.administrative_area_level_1) { formatted.push(shortNames.administrative_area_level_1); } if (shortNames.country) { formatted.push(shortNames.country); } googlejson.results[0].formatted_address = formatted.join(", "); cbk(null, googlejson); }); }); }; ================================================ FILE: providers/google.js ================================================ var request = require("request"); var _ = require('underscore'); exports.geocode = function ( providerOpts, loc, cbk, opts ) { var options = _.extend({sensor: false, address: loc}, opts || {}); var uri = "http" + ( options.key ? "s" : "" ) + "://maps.googleapis.com/maps/api/geocode/json" request({ uri: uri, qs:options }, function(err,resp,body) { if (err) return cbk(err); var result; try { result = JSON.parse(body); } catch (err) { cbk(err); return; } cbk(null,result); }); }; exports.reverseGeocode = function ( providerOpts, lat, lng, cbk, opts ) { var options = _.extend({sensor: false, latlng: lat + ',' + lng}, opts || {}); var uri = "http" + ( options.key ? "s" : "" ) + "://maps.googleapis.com/maps/api/geocode/json" request({ uri:uri, qs:options }, function(err,resp,body) { if (err) return cbk(err); var result; try { result = JSON.parse(body); } catch (err) { cbk(err); return; } cbk(null,result); }); }; ================================================ FILE: providers/yahoo.js ================================================ // xml2js is optional because only needed for geonames support var xml2js = require("xml2js"); var request = require("request"); var _ = require('underscore'); exports.geocode = function ( providerOpts, loc, cbk, opts ) { var options = _.extend({q: loc, flags: "J", appid:providerOpts.appid||"[yourappidhere]" }, opts || {}); request({ uri:"http://where.yahooapis.com/geocode", qs:options }, function(err,resp,body) { if (err) return cbk(err); var result; try { result = JSON.parse(body); } catch (err) { cbk(err); return; } cbk(null,result); }); }; // yahoo placefinder api http://developer.yahoo.com/geo/placefinder/guide/ exports.reverseGeocode = function ( providerOpts, lat, lng, cbk, opts ) { var options = _.extend({q: lat+", "+lng, gflags:"R", flags: "J", appid:providerOpts.appid||"[yourappidhere]" }, opts || {}); request({ uri:"http://where.yahooapis.com/geocode", qs:options }, function(err,resp,body) { // console.log("[GEOCODER Yahoo API] uri:", "http://where.yahooapis.com/geocode"); // console.log("[GEOCODER Yahoo API] options:", JSON.stringify(options)); // console.log("[GEOCODER Yahoo API] body:", body); if (err) return cbk(err); var result; try { result = JSON.parse(body); } catch (err) { cbk(err); return; } // Transform yahoo' structure into something that looks like Google's JSON outpu // https://developers.google.com/maps/documentation/geocoding/#JSON var googlejson = { "status":"OK", "results":[ { "address_components":[], "formatted_address":"", "geometry":{ "location":{ "lat":lat, "lng":lng } } } ] }; if (result.ResultSet.Error !== "0" && result.ResultSet.Error !== 0) { console.log("[GEOCODER Yahoo API] ERROR", result.Error, result.ErrorMessage); return cbk(result.ResultSet.ErrorMessage); } var a = null; // Yahoo seems to change its response format "randomly". So, sometimes, it there is only one result, // it will be in ResultSet.Result, and sometimes, in ResultSet.Results[0] if (undefined !== result.ResultSet.Result) { a = result.ResultSet.Result; } else if (result.ResultSet.Results && result.ResultSet.Results.length) { a = result.ResultSet.Results[0]; } if (!a) { return cbk("Error getting results from Yahoo API"); } if (a.house) googlejson.results[0].address_components.push({ "long_name":a.house, "short_name":a.house, "types":["street_number"] }); if (a.street) googlejson.results[0].address_components.push({ "long_name":a.street, "short_name":a.street, "types":["route"] }); if (a.city) googlejson.results[0].address_components.push({ "long_name":a.city, "short_name":a.city, "types":["locality", "political"] }); if (a.state) googlejson.results[0].address_components.push({ "long_name":a.state, "short_name":a.statecode || a.state, "types":[ "administrative_area_level_1", "political" ] }); if (a.county) googlejson.results[0].address_components.push({ "long_name":a.county, "short_name":a.countycode || a.county, "types":[ "administrative_area_level_2", "political" ] }); if (a.country) googlejson.results[0].address_components.push({ "long_name":a.country, "short_name":a.countrycode, "types":[ "country" ] }); if (a.postal) googlejson.results[0].address_components.push({ "long_name":a.postal, "short_name":a.postal, "types":[ "postal_code" ] }); if (a.latitude) googlejson.results[0].geometry.location = { "lat":parseFloat(a.latitude), "lng":parseFloat(a.longitude) }; // Make a formatted address as well as we can var formatted = []; if (a.line1) formatted.push(a.line1); if (a.line2) formatted.push(a.line2); if (a.line3) formatted.push(a.line3); if (a.line4) formatted.push(a.line4); googlejson.results[0].formatted_address = formatted.join(", "); // console.log("[GEOCODER Yahoo API], calling callback w/", JSON.stringify(googlejson)); cbk(null, googlejson); }); }; ================================================ FILE: test/geocoder-geonames-test.js ================================================ geocoder = require('../index.js'); module.exports = { setUp:function(cb) { geocoder.selectProvider("geonames",{"username":"npmunittests"}); cb(); }, testExposeGeocodeFunction: function(test){ test.equal(typeof geocoder.geocode, 'function'); test.equal(geocoder.provider, 'geonames'); test.done() }, // Uses "geonames" testReverseGeocode: function(test){ return require('./geocoder-google-test.js').testReverseGeocode(test); }, // Uses "address" testReverseGeocodeGoogleplex: function(test){ return require('./geocoder-google-test.js').testReverseGeocodeGoogleplex(test); }, } ================================================ FILE: test/geocoder-google-test.js ================================================ geocoder = require('../index.js'); module.exports = { setUp:function(cb) { geocoder.selectProvider("google"); cb() }, testExposeGeocodeFunction: function(test){ test.equal(typeof geocoder.geocode, 'function'); test.equal(geocoder.provider, 'google'); test.done() }, testGeocode: function(test){ test.expect(3); geocoder.geocode("Munich, Germany", function(err, result){ test.ok(!err); test.equals('OK', result.status); test.ok(result.results[0].formatted_address.match(/Munich/)); test.done(); }); }, testReverseGeocode: function(test){ test.expect(7); geocoder.reverseGeocode(49.101,6.1442, function(err, result){ test.ok(!err); test.equals('OK', result.status); // console.error(result.results[0].formatted_address); test.ok(result.results[0].formatted_address.match(/Montigny-lès-Metz/i)); result.results[0].address_components.forEach(function(ac) { if (ac.types.indexOf("locality")>=0) { test.ok(ac.short_name.match(/^Montigny-lès-Metz$/i)); } if (ac.types.indexOf("country")>=0) { test.equals(ac.short_name,"FR"); test.equals(ac.long_name,"France"); } if (ac.types.indexOf("administrative_area_level_1")>=0) { test.equals(ac.short_name,"Lorraine"); } }); test.done(); }); }, testReverseGeocodeGoogleplex: function(test){ test.expect(9); geocoder.reverseGeocode(37.42291810, -122.08542120, function(err, result){ test.ok(!err); test.equals('OK', result.status); test.ok(result.results[0].formatted_address.match(/Mountain View/i)); result.results[0].address_components.forEach(function(ac) { if (ac.types.indexOf("locality")>=0) { test.equals(ac.short_name,"Mountain View"); } if (ac.types.indexOf("country")>=0) { test.equals(ac.short_name,"US"); test.equals(ac.long_name,"United States"); } if (ac.types.indexOf("route")>=0) { test.ok(ac.short_name.match(/^Amphitheatre Pk(w?)y$/i)); } if (ac.types.indexOf("administrative_area_level_1")>=0) { test.equals(ac.short_name,"CA"); test.equals(ac.long_name,"California"); } }); test.done(); }); }, testLanguage: function(test){ test.expect(3); geocoder.geocode("Plattlinger Str. 10, 81479 München, Deutschland", function(err, result){ test.ok(!err); test.equals('OK', result.status); test.ok(result.results[0].formatted_address.match(/München/)); test.done(); }, {language: 'de'}); } } ================================================ FILE: test/geocoder-yahoo.js ================================================ geocoder = require('../index.js'); module.exports = { setUp:function(cb) { geocoder.selectProvider("yahoo",{"appid":"[yourappidhere]"}); cb(); }, testExposeGeocodeFunction: function(test){ test.equal(typeof geocoder.geocode, 'function'); test.equal(geocoder.provider, 'yahoo'); test.done() }, testReverseGeocode: function(test){ return require('./geocoder-google-test.js').testReverseGeocode(test); }, testReverseGeocodeGoogleplex: function(test){ return require('./geocoder-google-test.js').testReverseGeocodeGoogleplex(test); }, }