• Stars
    star
    641
  • Rank 67,774 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 11 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

CDNJS npm release license
© 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...

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.

More Repositories

1

accesscontrol

Role and Attribute based Access Control for Node.js
TypeScript
2,132
star
2

docma

A powerful tool to easily generate beautiful HTML documentation from JavaScript (JSDoc), Markdown and HTML files.
JavaScript
330
star
3

invert-color

Generates inverted (opposite) version of the given color. (<1KB)
TypeScript
288
star
4

tasktimer

An accurate timer utility for running periodic tasks on the given interval ticks or dates. (Node and Browser)
TypeScript
121
star
5

perfy

A simple, light-weight NodeJS utility for measuring code execution in high-resolution real times.
JavaScript
55
star
6

jsonc

Everything you need in JSON land.
TypeScript
38
star
7

grunt-jasmine-nodejs

[DEPRECATED] Jasmine (v2.x) Grunt multi-task for NodeJS with built-in reporters such as Default (Console) Reporter, JUnit XML, NUnit XML, Terminal Reporter, TeamCity, TAP Reporter. Supports the latest Jasmine features: fdescribe, fit, beforeAll, afterAll, etc...
JavaScript
35
star
8

custom-error-test

Compare and test various custom error implementations.
JavaScript
33
star
9

alfred-video-downloader

Video Downloader is an Alfred workflow written in Bash/Shell for easily downloading videos (and/or extracting audio) from various websites such as YouTube, Vimeo, DailyMotion and more...
Shell
32
star
10

jasmine-console-reporter

Progressive Console Reporter for Jasmine. Outputs detailed test results to the console, with beautiful layout and colors.
JavaScript
32
star
11

notation

Utility for modifying / processing the contents of Javascript objects via object notation strings or globs.
JavaScript
28
star
12

jsdoc-x

Parser for outputting a Javascript object from documented code via JSDoc's explain (-X) command.
JavaScript
13
star
13

re

RegExp API for Humans!
JavaScript
4
star
14

json-more

Deprecated. Use jsonc instead.
JavaScript
3
star
15

grunt-docma

DEPRECATED! Instead use Docma in your npm scripts.
JavaScript
2
star
16

ocli

CLI tools for most used operations and development workflows.
JavaScript
1
star
17

onury.github.io

Documentation for my libraries, apps...
HTML
1
star
18

tilo

Tiny logger with styles and levels for Node/TypeScript.
TypeScript
1
star