Giter Club home page Giter Club logo

geonames.js's Introduction

geonames.js v3.0.3 NEW (see changelog)

geonames.js is a flexible library for browser and Nodejs built on top geonames.org webservices.

It provides a simple API to dynamically fetch countries, states, regions, cities and other milion geographical names.

not found not found not found

img



1. Installation

npm install --save geonames.js

or

yarn add geonames.js

2. Requirements

You have to register (it's free) on Geonames.org in order to get the username that will be necessary for the API to work.

geonames.js depends on a native ES6 Promise implementation to be supported. If your environment doesn't support ES6 Promises, you can use a polyfill.

3. Usage:

You can fetch almost anything by taking advantage of the huge amount of information provided by geonames.org. It contains over 10 million geographical names and consists of over 9 million unique features whereof 2.8 million populated places and 5.5 million alternate names.

The list of available options in the API is in here under the webservice column.

  • Import the library:

    • server usage (NodeJS)
       const { Geonames } = require('geonames.js') /* commonJS */
    • browser usage (React, Angular, Vue etc.)
       import Geonames from 'geonames.js'; /* es module */
  • Usage:

    Initialize the Geoames using your settings:

    free WS

    const geonames = Geonames({
      username: 'myusername',
      lan: 'en',
      encoding: 'JSON'
    });

    commercial WS

    To use the commercial tier just define your token:

    const geonames = Geonames({
      username: 'myusername',
      token: 'mytoken',
      lan: 'en',
      encoding: 'JSON'
    });

    Since the library return promises, you can use either async/await or promise-based syntax

    plain call

    // async/await
    try{
      const continents = await geonames.search({q: 'CONT'}) //get continents
    }catch(err){
      console.error(err);
    }
    
    // promise
    geonames.search({q: 'CONT'}) //get continents
    .then(resp => {
      console.log(resp.geonames);
    })
    .catch(err => console.error(err));

    chaining calls

    // async/await
    try{
      const countries = await geonames.countryInfo({}) //get continents
      const states = await geonames.children({geonameId: countries.geonames[0].geonameId})
      const regions = await geonames.children({geonameId: states.geonames[0].geonameId});
      const cities = await geonames.children({geonameId: regions.geonames[0].geonameId});
      console.log(cities.geonames);
    }catch(err){
      console.error(err);
    }
    
    // promise
    geonames.countryInfo({}) 
    .then(countries => {
      return geonames.children({geonameId: countries.geonames[0].geonameId})
    })
    .then(states => {
      return geonames.children({geonameId: states.geonames[0].geonameId});
    })
    .then(regions => {
      return geonames.children({geonameId: regions.geonames[0].geonameId});
    })
    .then(cities => {
      console.log(cities.geonames);
    })
    .catch(err => console.log(err));

4. Contribution:

Feel free to contribute; any help is really appreciated :)

run with:

yarn build-dev (dev bundle)
yarn build (prod bundle)
yarn build:all (both - for packaging)
USERNAME=myusername yarn test (unit testing)

5. Changelog v3.0.3:

  • Added support for latest Geonames api (address, geoCodeAddress, streetNameLookup)
  • Added typescript autocomplete for all the api's
  • change function constructor to plain function
  • updated dependencies

img


6. License:

MIT 2017 License Karim Abdelcadir

geonames.js's People

Contributors

kinotto avatar xavitorello avatar lamuertepeluda avatar dependabot[bot] avatar piperchester avatar josephfrazier avatar natim avatar

Stargazers

Evance Osoo avatar Justus  avatar Alex Lazarev avatar  avatar Gabs avatar  avatar  avatar  avatar Akshay Tare avatar Vivien Tassing avatar Ryan Waldon avatar Eaton avatar Felipe avatar Ricardo avatar  avatar Behzad Eshan avatar Méhész Pál avatar  avatar Roman Liuk avatar Pablo Cerda avatar  avatar Alexander avatar Luis Sandoval avatar Coco Guerra avatar Edward Tan avatar Wian Lloyd avatar Marcelo Fernando Scarpim avatar Tamal Govinda das avatar Ian Flournoy avatar Jeff Fairley avatar Rohit Gohri avatar Farimah Karimi avatar LaughingBubba avatar Jon Repp avatar Andrey Pervakov avatar Maria Latysheva avatar José Silva avatar Jeremy E avatar Nilton Adolar Ropelato Júnior avatar Iván Arcuschin avatar Mihai Tomescu avatar Belinda Caylor avatar Lucas Reis avatar Michal Gallovič avatar Christian Michels avatar  avatar cbp44-prenetics avatar megaorca avatar Rish avatar xeetzer avatar  avatar Emanuel Fernandes avatar  avatar Murilo Monteiro Ribas avatar Jimmy Rios Leung avatar Kit avatar Lucas Teotônio Lima avatar  avatar Jonathan Puckey avatar Sergey avatar Rodrigo Antinarelli avatar Joel Hickok avatar Guido García avatar  avatar Mark Vayngrib avatar Herman Leus avatar Sebastian Krzyżanowski avatar Glenn Jorde avatar Rasheed Bustamam avatar  avatar Giacomo Zinetti avatar El Hombre avatar Elodie avatar Maurus Vitor avatar John Arkema avatar Haves avatar  avatar Gabriele Giuranno avatar Manuel Kanah avatar Philipp Kursawe avatar Necmettin Begiter avatar 深山猎人 avatar Daniel Blendea avatar Joe Kendall avatar Stefano Vollono avatar Antonio Polese avatar Hakim Abdelcadir avatar

Watchers

James Cloos avatar  avatar Lucas Teotônio Lima avatar Thomas Poppe avatar

geonames.js's Issues

Geonames is not a function

Hello,

following the indications of the readme I get the following error message. TypeError: Geonames is not a function
The lib usage changed ?

const { Geonames } = require('geonames.js')

this.geoNameClient = Geonames({
    username: 'xxxx',
    lan: 'en',
    encoding: 'JSON'
  });

Thanks!

docs: potentially a note about importing into a TSX app?

Using a freshly installed TSX app through create-react-app, I tried importing the lib with

import Geonames from 'geonames.js';

but I get the dreaded

Could not find a declaration file for module 'geonames.js'. ... implicitly has an 'any' type.

Maybe we could add to the Readme about this to warn users?

Doesn't work with import es module

Hi,

I'm building a node server with typescript, and I create a service that wraps a geoname client in its instance and it works if I use require option like my ts file below

const Geonames = require('geonames.js');

export class GeonamesService {

  private static _instance: GeonamesService;
  private geonamesClient;

  constructor() {
      this.geonamesClient = new Geonames({
        username: "username",
        lan: 'en',
        encoding: 'JSON'
      });
  }

  static get(): GeonamesService {
    if (!this._instance) {
      this._instance =  new GeonamesService();
    }
    return this._instance;
  }

  public async getCountries() {
      const countries = await this.geonamesClient.countryInfo({});
      console.log(countries);
      return countries;
  }


}


If I use

import { Geonames } from 'geonames.js';

It throws an error when it's doing the new Geonames config..

'TypeError: geonames_js_1.Geonames is not a constructor'

Any idea what I'm doing wrong or it's a bug?

Access-Control-Allow-Origin

Hi,
I got an error when I try to fetch some data with the geoname.contryInfo({}) function.

Here is the error message:
XMLHttpRequest cannot load http://api.geonames.org/countryInfoJSON?formatted=true&style=full&username=username&lang=en. The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:3000' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

Vulnerability issues

Hello,
in my project I have some vulnerabilities that depends on your library (see logs below).

They depend on the use of old version of the hawk library imported by request.
They already solved the problem because, since version 2.87, request is using a local implementation of hawk.

I see that you recently downgraded request to 2.81.
Why this downgrade? Any chances to upgrade to 2.87 and solve the vulnerability issue?


LOGS coming from npm audit

┌───────────────┬──────────────────────────────────────────────────────────────┐
│ moderate      │ Prototype pollution                                          │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package       │ hoek                                                         │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ geonames.js                                                  │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path          │ geonames.js > request > hawk > boom > hoek                   │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info     │ https://nodesecurity.io/advisories/566                       │
└───────────────┴──────────────────────────────────────────────────────────────┘
┌───────────────┬──────────────────────────────────────────────────────────────┐
│ moderate      │ Prototype pollution                                          │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package       │ hoek                                                         │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ geonames.js                                                  │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path          │ geonames.js > request > hawk > cryptiles > boom > hoek       │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info     │ https://nodesecurity.io/advisories/566                       │
└───────────────┴──────────────────────────────────────────────────────────────┘
┌───────────────┬──────────────────────────────────────────────────────────────┐
│ moderate      │ Prototype pollution                                          │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package       │ hoek                                                         │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ geonames.js                                                  │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path          │ geonames.js > request > hawk > hoek                          │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info     │ https://nodesecurity.io/advisories/566                       │
└───────────────┴──────────────────────────────────────────────────────────────┘
┌───────────────┬──────────────────────────────────────────────────────────────┐
│ moderate      │ Prototype pollution                                          │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package       │ hoek                                                         │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ geonames.js                                                  │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path          │ geonames.js > request > hawk > sntp > hoek                   │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info     │ https://nodesecurity.io/advisories/566                       │
└───────────────┴──────────────────────────────────────────────────────────────┘

401 Error

I created my account with my username. When I used that username it giving 401 error code

Suggestion for v2.0 (ES6+ version)

Hey there,

I was trying to use your library, but I had some difficult importing it using my module bundler (webpack).

So after some time I gave up and rewrote it entirely using a more modern syntax. I wanted to share this with you, since I tried to make it backward compatible (although compatibility is 100% untested) and it seems to work. I used axios, a promise based ajax library which works well on both browser and node. So you could drop a bunch of superseeded dependencies.

I also added the HTTPS endpoint as baseURL since it's more suited for modern websites.

See the code and how it works on StackBlitz: https://stackblitz.com/edit/js-hqzhep?file=Geonames.js

If you think ES5 compatibility is important, we can make a webpack config file for transpiling it.

Feel free to use this code to make a new version of this library if you wish.

Anyway to cache results?

The app I'm building will most likely reuse the same result sets once they're fetched once. I don't think there's a way to do opaque caching with geoname.js, but it would be super convenient if there was

GeocodeAddress doesn't exists

Hi,

I'm using the library with typescript and my geonames client doesn't contains the geocodeAddress method.

http://api.geonames.org/geoCodeAddressJSON?q=Museumplein+6+amsterdam&username=demo

The library contains a geocode method but after send the request it returns a 404 error.

'<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL /geocodeJSON was not found on this server.</p>
</body></html>

I think that the included method in the library must be updated to pointing at geoCodeAddress web service method. (/geoCodeAddressJSON)

Thanks!

Cannot read property 'create' of undefined

HI
I am trying to use geonames.js in browser.
I am on local machine and address in browser is http://localhost:57745/index.html
Following is my code.

<script type="text/javascript" src="geonames.min.js"></script>

<button type="button" class="btn btn-primary" onclick="getCities()">getCities</button>

async function getCities () {
            const geonames = new Geonames({ username: 'myusername', lan: 'en', encoding: 'JSON' });
            try {
                const countries = await geonames.countryInfo({}) //get continents
                const states = await geonames.children({ geonameId: countries.geonames[0].geonameId })
                const regions = await geonames.children({ geonameId: states.geonames[0].geonameId });
                const cities = await geonames.children({ geonameId: regions.geonames[0].geonameId });
                console.log(cities.geonames);
                $("#geo").text(cities.geonames);

            } catch (err) {
                console.error(err);
            }

        };

I am getting this error

geonames.min.js:1 Uncaught (in promise) TypeError: Cannot read property 'create' of undefined
    at new c (geonames.min.js:1)
    at getCities (index.html:357)
    at HTMLButtonElement.onclick (index.html:141)
c @ geonames.min.js:1
getCities @ index.html:357
onclick @ index.html:141

This is my first time using this library. Any help please.
Zeni

Duplicate Countries

When using the api to get all the countries
const countries = await geoNames.countryInfo({}) //get continents

I'm getting duplicate countries

You may need an appropriate loader to handle this file type

I use Geonames for my React project, my package.json dependencies:

"dependencies": {
    "bluebird": "^3.5.1",
    "bootstrap": "^3.3.7",
    "chart.js": "^2.7.2",
    "classnames": "^2.2.5",
    "convert-units": "^2.3.4",
    "currency-formatter": "^1.3.1",
    "file-saver": "^1.3.3",
    "fixed-data-table-2": "^0.8.15",
    "font-awesome": "^4.7.0",
    "geonames.js": "^2.3.0",
    "isomorphic-fetch": "^2.2.1",
    "jquery": "^3.1.1",
    "lodash": "^4.17.4",
    "moment": "^2.19.2",
    "moment-range": "^3.0.3",
    "moment-timezone": "^0.5.14",
    "object-assign": "^4.1.1",
    "prop-types": "^15.6.0",
    "query-string": "^5.0.1",
    "react": "^16.3.0",
    "react-addons-css-transition-group": "^15.6.2",
    "react-autosuggest": "^9.3.2",
    "react-bootstrap": "^0.31.5",
    "react-bootstrap-timezone-picker": "^1.0.12",
    "react-chartjs-2": "^2.7.4",
    "react-country-region-selector": "^1.2.3",
    "react-datetime": "^2.11.0",
    "react-dom": "^16.3.0",
    "react-dom-factories": "^1.0.2",
    "react-flag-icon-css": "^1.0.23",
    "react-google-maps": "^9.4.3",
    "react-helmet": "^5.2.0",
    "react-hotkeys": "^0.10.0",
    "react-input-autosize": "^2.1.2",
    "react-intl-tel-input": "^5.0.7",
    "react-jss": "^8.4.0",
    "react-moment": "^0.6.8",
    "react-notifications": "^1.3.0",
    "react-onclickoutside": "^6.7.0",
    "react-overlays": "^0.8.3",
    "react-redux": "^5.0.3",
    "react-redux-i18n": "^1.9.1",
    "react-router": "^3.2.0",
    "react-router-redux": "^4.0.8",
    "react-script-loader": "0.0.1",
    "react-select": "^1.0.0-rc.10",
    "react-spinners": "^0.3.2",
    "react-style-proptype": "^3.1.0",
    "react-timeago": "^3.3.0",
    "react-transition-group": "^2.3.1",
    "redux": "^3.6.0",
    "redux-logger": "^2.8.2",
    "redux-thunk": "^2.2.0",
    "shallowequal": "^1.0.2",
    "socket.io": "1.7.3",
    "socket.io-client": "1.7.3",
    "toetag": "^3.3.7",
    "underscore.deferred": "^0.4.0",
    "uuid": "^3.1.0"
  },
  "devDependencies": {
    "babel-eslint": "^10.0.1",
    "case-sensitive-paths-webpack-plugin": "^2.0.0",
    "babel-plugin-import": "^1.6.5",
    "babel-plugin-module-resolver": "^3.1.0",
    "babel-plugin-styled-components": "^1.8.0",
    "babel-plugin-wrap-in-js": "^1.1.1",
    "eslint": "^5.7.0",
    "eslint-config-airbnb": "^17.1.0",
    "eslint-config-prettier": "^3.1.0",
    "eslint-plugin-import": "^2.14.0",
    "eslint-plugin-jsx-a11y": "^6.1.2",
    "eslint-plugin-prettier": "^3.0.0",
    "eslint-plugin-react": "^7.11.1",
    "eslint-plugin-react-hooks": "^1.5.0",
    "node-sass-chokidar": "^1.3.3",
    "npm-run-all": "^4.1.3",
    "prettier": "^1.16.4",
    "react-scripts": "0.9.4"
  }

And I import to my jsx files:
import Geonames from 'geonames.js';
But I get error:

Failed to compile.

Error in ./~/geonames.js/dist/geonames.min.js
Module parse failed: D:\project\reactclient\node_modules\geonames.js\dist\geonames.min.js Unexpected token (1:2024)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (1:2024)
 @ ./src/containers/settings/general/Settings/index.js 84:15-37

How can I fix it ?

Cannot enter multiple featureCodes

I am looking to pass multiple featureCodes as params to the search api end point. I don't seem to be able to do this?

Example:

this.geonames.search({ country: country, q: search, featureCode: 'ADM2', featureCode: 'ADM1' })

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.