Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

geolocator

onury9.6kMIT2.1.5

A utility for getting geo-location information via HTML5 and IP look-ups, geocoding, address look-ups, distance and durations, timezone information and more...

geo, geolocation, location, position, latitude, longitude, HTML5, google, map, geocode, reverse-geocode, ip, address, lookup, distance, directions, duration, matrix, route, timezone, lat, lng, lon

readme

CDNJS npm release release license maintained
© 2019, Onur Yıldırım (@onury). Please see the Disclaimer and License.


Geolocator.js is a utility for getting geo-location information, geocoding, address look-ups, distance & durations, timezone information and more...

Features

  • HTML5 geolocation (by user permission) with improved accuracy.
  • Location by IP
  • Reverse Geocoding (address lookup)
  • Full address information (street, town, neighborhood, region, country, country code, postal code, etc...)
  • Fallback mechanism (from HTML5-geolocation to Geo-IP lookup)
  • Watch geographic position
  • Locate by mobile information
  • Get timezone information
  • Get distance matrix and duration information
  • Calculate distance between two geographic points
  • Various geographic conversion utilities
  • Get client IP
  • Fetched location includes country flag image (SVG) URL
  • Language support (depends on the service provider)
  • Supports Google Loader (loads Google APIs dynamically)
  • Dynamically create Google Maps, on demand (with marker, info window, auto-adjusted zoom)
  • Get static Google Map (image) URL for a location
  • Non-blocking script loading (external sources are loaded on the fly without interrupting page load)
  • No library/framework dependencies (such as jQuery, etc...)
  • Universal module (CommonJS/AMD..)
  • Small file size (9KB minified, gzipped)
  • Browser Support: IE 9+, Chrome, Safari, Firefox, Opera...

See a Live Demo.

Get Geolocator.js

  • Link or download via CDNJS.
  • Download full source code from GitHub releases.
  • Install via Bower: bower install geolocator
  • Install via NPM: npm install geolocator

Usage:

Example below, will attempt to get user's geo-location via HTML5 Geolocation and if user rejects, it will fallback to IP based geo-location.

Inside the <head> of your HTML:

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

    geolocator.config({
        language: "en",
        google: {
            version: "3",
            key: "YOUR-GOOGLE-API-KEY"
        }
    });

    window.onload = function () {
        var options = {
            enableHighAccuracy: true,
            timeout: 5000,
            maximumWait: 10000,     // max wait time for desired accuracy
            maximumAge: 0,          // disable cache
            desiredAccuracy: 30,    // meters
            fallbackToIP: true,     // fallback to IP if Geolocation fails or rejected
            addressLookup: true,    // requires Google API key if true
            timezone: true,         // requires Google API key if true
            map: "map-canvas",      // interactive map element id (or options object)
            staticMap: true         // get a static map image URL (boolean or options object)
        };
        geolocator.locate(options, function (err, location) {
            if (err) return console.log(err);
            console.log(location);
        });
    };

</script>

If you've enabled map option; include the following, inside the <body> of your HTML:

<div id="map-canvas" style="width:600px;height:400px"></div>

Read API documentation for lots of other features and examples.

Important Notes

  • Since Geolocation API is an HTML5 feature, make sure your doctype is HTML5 (e.g. <!DOCTYPE html>).
  • Make sure you're calling Geolocation APIs (such as geolocator.locate() and geolocator.watch()) from a secure origin (i.e. an HTTPS page). In Chrome 50+, Geolocation API is removed from unsecured origins. Other browsers are expected to follow.
  • Although some calls might work without a key, it is generally required by most Google APIs (such as Time Zone API). To get a free (or premium) key, click here. After getting a key, you can enable multiple APIs for it. Make sure you enable all the APIs supported by Geolocator. (If you don't have a key, you can still use Geolocator like the previous versions, but with limited features.)
  • Geolocator now uses a single Geo-IP provider (GeoJS for locating by IP. You can use geolcoator.setGeoIPSource() method to set a different Geo-IP source, but see the Caveats section before you do so.
  • Most importantly; please use this library for anonymous usage data only. And get consent from your users that you're collecting their personal data and present your reasons.

Caveats

  • Mixed Content Restriction:

    There are alternative Geo-IP services to be used with this library. But most of these services do not provide a free API over HTTPS (SSL/TLS). You need to subscribe for a premium API key to use HTTPS. The caveat is; HTML5 Geolocation API is restricted to HTTPS and when you enable the fallbackToIP option, some browsers (such as Chrome and Firefox) will not allow mixed content. It will block HTTP content when the page is served over HTTPS.

    Currently, Geolocator will use GeoJS by default which is free and supports HTTPS. Please use this service responsibly. For example, do NOT call locate() or .locatebyIP() on every user/request but only on site entrance. Their location or IP will not change suddenly unless they can teleport!..

    Also, support GeoJS if you can so we can continue using this nice free service. If you know other free Geo-IP services over HTTPS, let me know and we can add/use them as alternatives.

  • Isomorphic Applications / SSR Support:

    This library currently only works on client-side (browser). Any kind of server-side functionality (including Server Side Rendering) is not yet oficially supported.

    There is a discussion about at least preventing it from throwing on server; or maybe adding support for some (if not all) methods to work on server. If you're interested and willing to contribute;

    • Continue discussion on this thread,
    • PRs are welcome since I need help improving and maintaining this library.

Under the Hood

Geolocator v2 is written in ES2015 (ES6), compiled with Babel, bundled with Webpack and documented with Docma.

Change Log

See version changes here.

License

MIT. See the Disclaimer and License.

changelog

Geolocator Changelog:

All notable changes to this project will be documented in this file. The format is based on Keep a Changelog and this project adheres to Semantic Versioning.

2.1.5 (2019-01-09)

Fixed

  • An issue where locateByIP() method would fail due to external service being shut down. Added a new (default) Geo-IP service provider to GeoJS with HTTPS support.
  • An issue where XHR request handlers would not be invoked in IE9.

Changed

  • getIP() method now uses XHR request instead of JSONP, since CORS is supported by the service.
  • Added ability fetch location-by-IP data via XHR. (Set xhr to true when passing a new Geo-IP source to setGeoIPSource() method.)
  • Default value for timeout option is changed to 6000 for .locate() method.
  • Improved minification and reduced library size.
  • (Dev) Removed grunt in favour of npm scripts. Removed Jasmine in favour of Jest.

2.1.3 (2018-04-02)

Fixed

  • Changed default Geo-IP provider to nekudo/shiny_geoip. (FreeGeoIP service is shut down). Fixes issue #53.
  • An issue with Geo-IP schema, occurred when a function is used instead of a mapper object.

Added

  • Geo IP source: IPStack (requires a free API key). Note that this is a separate file, you can include in your HTML. Or you can use a different provider if you like. See the Caveats section before you do so.

2.1.1 (2017-03-11)

Added

  • Support for hybrid or sandboxed environments (such as Electron). Now, forcing the export mechanism to assign geolocator to window even if it's used via an import or require statement. i.e. this happens when used within babel/webpack bundled code or from within an electron app. See issues #42 and #48.

Changed

  • Minor revision, clean up.

2.1.0 (2016-09-30)

Please read the API documentation.

Added

  • Ability to get static Google Maps (image) via .getStaticMap() method. #34. Make sure you have enabled Google Static Maps API in Google Developers console.
  • Ability to style Google Maps. Either set global styles via geolocator.config() or corresponding methods such as .createMap() or .getStaticMap().

Changed

  • Improved desired accuracy logic. Added maximumWait:Number and onProgress:Function options for .locate() method.
  • Minor revisions, updated dev-dependencies.

Fixed

  • Changed Geo-IP provider to FreeGeoIP. (Wikimedia has shutdown the geo service.) Fixes issue #36.
  • Respecting countries with states, other than US. Fixes #37.

2.0.0 (2016-06-25)

Please read the API documentation.

Added

  • Feature: Watch geographic position.
  • Feature: Locate by mobile information.
  • Feature: Get timezone information. Fixes issue #13.
  • Feature: Get distance matrix and duration information.
  • Feature: Calculate distance between two geographic points.
  • Feature: Various geographic conversion utilities.
  • Feature: Get client IP.
  • Feature: Fetched location includes country flag image (SVG) URL.
  • Feature: Language support (depends on the service provider). Fixes issue #20.
  • Feature: Universal module (CommonJS/Node/AMD..). Fixes issue #16.
  • Support multiple calls. Fixes issue #24.

Changed

  • BREAKING: Method signatures changed for .locate() and .locateByIP() methods.
  • BREAKING: Most features make use of Google APIs. So you'll need a (single) Google API key to use them all. If you don't have a key, you can still use Geolocator like the previous versions, but with limited features.
  • BREAKING: geolocator.location property is dropped. You can always access the result, via the second argument of each async method's callback. See documented examples.
  • Better Geolocation accuracy. Fixes issue #28.
  • Google Maps is no longer loaded by default. Depends on called methods or options.
  • Now, we only support a single Geo-IP source (Wikimedia). Can be set/changed via setGeoIPSource() method.

Fixed

  • An issue with wikimedia IP lookup. Fixes #32.

1.2.9

Added

  • HTTPS secure connection support for IP geo-sources. (Note: GeoPlugin does not support HTTPS. You should use FreeGeoIP or Wikimedia IP sources instead.). (Fixes Issue #11. PR: @iurisilvio)

1.2.8

Added

Changed

  • Removed the sensor parameter from Goole Maps loader, since it's not required anymore.
  • Bumped Google Maps version to 3.18.

1.2.6

Added

  • FNew method: isPositionError().

Changed

  • The recent Error or PositionError (HTML5) is passed to error callbacks instead of String error message. See updated documentation. Fixes issue #7. (This shouldn't be a breaking-change but do test your app if you decide to upgrade.)
  • Updated example. (Enable/disable HTML5-to-IP fallback.)

1.2.4

Changed

  • Source scripts are now automatically removed from DOM after result is received.
  • Changed default IP source to GeoPlugin (index:1); since FreeGeoIP is occasionally down these days.

Fixed

  • errorCallback would not be invoked if IP geo-source service is not available. Fixes issue #6.

1.2.1

Added

1.2.0

Changed

  • Code revisions, optimizations.
  • Now loads the latest release version of Google Maps (3.15).

1.1.0

Changed

  • JSLint compliant code.
  • Minor code revisions.

0.9.5

Changed

  • Google has deprecated google.loader.ClientLocation API. As a result; Google (Loader) is removed from IP-Geo Sources.
  • Indexes changed for IP-Geo sources. New Indexes: FreeGeoIP (0), GeoPlugin (1), Wikimedia (2)