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