Giter Site home page Giter Site logo

onury / geolocator Goto Github PK

View Code? Open in Web Editor NEW
641.0 36.0 113.0 4.29 MB

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

Home Page: https://onury.io/geolocator

License: MIT License

JavaScript 87.00% HTML 12.12% Less 0.88%
geo-location address geocode timezone distance matrix coordinates html5 js

geolocator's Introduction

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.

geolocator's People

Contributors

iurisilvio avatar onury avatar peterdavehello avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

geolocator's Issues

Call onError with the full Error object

Hi there,

if you use the lib without IP Fallback, the error param from the onError callback is only the original error message. See this line. Wouldn't it be better to pass the whole error, so this would allow something like:

onGeolocationError: function(error) {
      switch (error.code) {
        case error.PERMISSION_DENIED:
        // ...
        case error.TIMEOUT:
        // ...
        case error.POSITION_UNAVAILABLE:
        // ...
    }

thoughts ?

Promises

Make geolocator with promises in the future?

Demo pages not using HTTPS

Hello,

As stated in your own README:

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.

Since the demo is not using HTTPS, the demo doesn't ask for location in Google Chrome.

Please put the demo pages under HTTPS, its free using Let's Encrypt now!

GeoIP, "Failed to load resource"

Hi!

I'm just keep getting "Failed to load resource" when I'm trying to get the location of my IP address through localhost. But when I go to http://freegeoip.net/json/?callback=geolocator.__ipscb the data shows correctly where my IP address are located, so to speak. I am using the original source code and I haven't edited anything, except for the street view option (hide / show the street view icon). I'm using version 1.1.

Forced to use Unrestricted Google API Key

Hi,

This is a great library and I really like to use this as the methods are very intuitive. However, the geocode method makes a Google Geocoding API call. Google has enforced that a web-api call should use IP Address Restricted Key (Server Key) - https://developers.google.com/maps/faq#switch-key-type. However, my requirement and that of this library's is to make the call from browser and therefore IP Address restricted key will not work.

Google has Javascript API for Geocoding which makes use of HTTP Referrer restriction. Instead of calling the WebAPI, I think we should call the Javascript API of Google's.

Either I am doing something wrong as everybody using this library will be facing the issue or consumers of this library are just using a unrestricted key. Can you please help?

Not working on IE8

When I try to run the provided example in IE 8 nothing happens.
I get an error on line 132: if (comp.types.indexOf('route') >= 0) {

Because indexOf() is not supported in IE <9

--EDIT--
Seems like row 290: delete window.Geo; is not working as well

navigator is not defined

Hi, I've been enjoying getting the geolocator integrated into my node project. I'm getting an unusual error, when attempting to run try the example in the "Guide" section:

Connect
500 ReferenceError: navigator is not defined
at Function.isGeolocationSupported (C:...\node_modules\geolocator\dist\geolocator.js:1845:21)
at Function.locate (C:...\node_modules\geolocator\dist\geolocator.js:719:29)

The "map-canvas" div is in a pug script, and this is the Javascript that's called by the GET request:

const geolocator = require('geolocator');

exports.getTestMap = (req, res) => {
  geolocator.config({
      language: "en",
      google: {
          version: process.env.GOOGLE_MAPS_VERSION,
          key: process.env.GOOGLE_MAPS_KEY
      }
  });
  var options = {
      enableHighAccuracy: false,
      timeout: 5000,
      maximumWait: 1500,     // max wait time for desired accuracy
      maximumAge: 0,          // disable cache
      desiredAccuracy: 100,    // meters
      fallbackToIP: true,     // fallback to IP if Geolocation fails or rejected
      addressLookup: false,    // requires Google API key if true
      timezone: false,         // requires Google API key if true
      map: "map-canvas",      // interactive map element id (or options object)
      staticMap: true         // map image URL (boolean or options object) // false => moveable marker?
  };
  // 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>
    geolocator.locate(options, function (err, location) {
      if (err) return console.log(err);
      console.log(location);
  });
  res.render('api/testmap', {
    title: 'testmap'
  }); 
};

I apologize if this is not an issue in the code itself, but I am stuck. . Is this enough information to tell if there's an issue? Thanks so much for any help!

Regards,

Issue with Firefox and HTML5 lookup error?

I have a simple locate script using the latest version of geolocator. When I run under Firefox 40.0 (on Mac OS), and either close the HTML5 location permission window or deny location access, I don't get a graceful degradation to IP-based lookup nor does it call my error function. It just seems to die quietly without any console messages.

I don't think I'm doing anything too egregiously stupid (famous last words!) because it works under Chrome/Mac, Safari/Mac, and IE8/Win7.

I tried setting up a jsfiddle, but was having problems with getting the external geolocator code to be included properly. So I set up a test case at http://www.fogbound.net/locate/

Enable the sharing location automatically

Hyy,
I want to enable browser geolaction automatically, as i am getting a confirmation dialog while accessing geolocation to allow or deny, i dont want any confirmation dialog.
I want this feature by coding
Please confirm

Language

Hey. If there is any way to control response language of json?

Locate on examples throws DomException

On the examples page, the first Locate throws an error:
VM51:47 Uncaught DOMException: Failed to execute 'postMessage' on 'Window': An object could not be cloned.(…)

I am using Chrome Version 54.0.2840.100 (64-bit).

fallbackToIP causes error

If you prevent the use of location services in the browser, an error gets thrown when fallbackToIP is set to true. "Cannot read property '_' of undefined"

It appears in the function

 notateGlobalObj: function notateGlobalObj(notation) {
		        notation = utils.trimDots(notation);
		        var levels = notation.split('.'),
		            o = window;
		        if (levels[0] === 'window' || levels[0] === 'document') {
		            levels.shift();
		        }
		        levels.forEach(function (note) {
		            o = o[note];
		        });
		        return o;
		    },

As the function iterates through the levels array, the variable o becomes undefined after the first iteration. Also the notation variable has a value of "geolocator._.cb" This code is trying to make an object key of '_' and I am not sure if that is intended.

thanks,

Typo in Documentation

Hey there,

Wanted to point out a little typo in the locateByIP method example...

geolocator.locateByIp(options, function (err, location) {
    console.log(err || location);
});

the "IP" portion should be uppercased

geolocator.locateByIP(options, function (err, location) {
    console.log(err || location);
});

Thanks for the great library!

CommonJS support

Since the package is on NPM, it would be nice if module.exports were utilized if available -- currently require('geolocator') returns undefined.

geo.helper.geocode raw flag logic

Hi, I'm trying to get google raw object from "locate" method.
Looking at the code, geocode method:

response = options.raw
                ? response
                : geoHelper.formatGeocodeResults(response.results);

options.raw will always be undefined. Should it not be conf.raw, that way we could set this flag in the Google Configuration:

               geoLocator.config({
                    language: "en",
                    google: {
                        version: "3",
                        key: key
                    },
                    raw: true
                });

Ideally raw should be attribute of the options, but this probably would require more rework to pass it to geocode method

The 'raw' option never gets to be used

Passing raw = true in the options for Gelolocate.locate does not have any effect when we have options.addressLookup set to true.

When addressLookup = true, the loc.coords object is passed to geolocator.reverseGeocode and at this point options.raw is lost.

Geolocation "timeout"

Hi,
when i try "geolocator.locate " function returns often "timeout" . First time works perfectly but if i reload function i get timeout.
Also on your site if you click on locate button you will get timeout of geolocator. How can i solve this?

Best regards

Crashes when used with Electron

Uncaught TypeError: Cannot read property '_' of undefined
    at /project/node_modules/geolocator/dist/geolocator.js:2989:19
    at Array.forEach (native)
    at Object.notateGlobalObj (/project/node_modules/geolocator/dist/geolocator.js:2988:17)
    at Function.jsonp (/project/node_modules/geolocator/dist/geolocator.js:3382:36)
    at Function.locateByIP (/project/node_modules/geolocator/dist/geolocator.js:986:37)
    at fallbackToIP (/project/node_modules/geolocator/dist/geolocator.js:704:40)
    at onPositionError (/project/node_modules/geolocator/dist/geolocator.js:716:18)
    at /project/node_modules/geolocator/dist/geolocator.js:2334:18
    at GeoWatcher.clear (/project/node_modules/geolocator/dist/geolocator.js:4933:30)
    at /project/node_modules/geolocator/dist/geolocator.js:2333:29

source:

import geolocator from 'geolocator';

geolocator.config({
  language: "en",
  google: {
    version: "3",
    key: googleApiKey
  }
});

    const options = {
      enableHighAccuracy: true,
      timeout: 5000,
      maximumWait: 10000,
      desiredAccuracy: 30,
      fallbackToIP: true, 
      addressLookup: true,
      timezone: true
    };

    geolocator.locate(options, (err, loc) => {
      console.log(err, loc);
    });

FreeGeoIP service is shut down

Hi Guys!

I've been had problems with the displaying of the map and I think is because FreeGeoIP has deprecated the API and now is called "IP Stack"; is on yours plans to fix this bug?

Server-side support

Hello!

This function brakes on server side because obviously navigator api isn't part of the NodeJS, but given the name of the function isGeolocationSupported isn't supposed to verify exactly this ?

static isGeolocationSupported() {

My proposal is to check the type of navigator keyworkd before use it like bellow:

return typeof navigator != 'undefined' && ('geolocation' in navigator);

That way the function will return false and won't break anymore :)

What do you think about?

Thanks

TypeError: geolocator.__glcb is not a function

I'm trying out the geolocator but I cannot get it to work within my project. I get two errors:

TypeError: geolocator.__glcb is not a function
jsapi?callback=geolocator.__glcb()jsapi?....__glcb (line 40)
[Break On This Error]

geolocator.__glcb();

and

TypeError: data is null
_buildLocation(sourceIndex=0, data=null)geolocator.js (line 287)
_gLoadCallback()geolocator.js (line 252)
[Break On This Error]

latitude: data.latitude,

Draggable marker

My users sometimes do not know the house number, only the street, and geolocation cannot be used.

I would love a feature where the address can be corrected by dragging the pin to the right place.

Uncaught TypeError: Cannot read property '_' of undefined(…)

Any ideas what I'm doing wrong? Or if this is a geolocator library bug? I only get this when blocking location usage in the browser (which kicks off the fallback functionality).

VM1457:2989 Uncaught TypeError: Cannot read property '_' of undefined(…)
(anonymous function) @ VM1457:2989
notateGlobalObj @ VM1457:2988
jsonp @ VM1457:3382
locateByIP @ VM1457:986
fallbackToIP @ VM1457:704
onPositionError @ VM1457:716

"geolocator":"2.1.0"

import geolocator from 'geolocator'

geolocator.config({
	language: "en"
});

var options = {
	enableHighAccuracy: false,
	timeout: 5000,
	maximumAge: 1800000,
	fallbackToIP: true
};
geolocator.locate(options, function (err, location) {
	...
}

Geocode a given address

Hey there, wonderful work on this library !

On the readme I can read Reverse Geocoding (address lookup) but can't find how to use this feature ? Basically I would like to enter an address and have it formatted the same way the location object is, as a fallback with user input. It would enable, from a simple address (like Champs-Elysée, Paris) to get the zip/postal code and more data like that. Is that possible ?

Better Fallback

The freegeoip has not a good accuracy.

Is it possible to fallback to the google api once the user deny getting coordinates by html5?

google.load("maps", "2.x", {callback: initialize});

function initialize() {
  if (google.loader.ClientLocation) {
      var lat = google.loader.ClientLocation.latitude;
      var long = google.loader.ClientLocation.longitude;
      console.log("lat: " + lat + "\nlong: " + long);
   }
   else { alert ("not available"); }
 }

request geolocation only IP ?

when the HTML 5 geolocation is used it takes a while to get the info I need. I'd like to only do the geolocation via ip as it is way faster. Is there a built in way to do so ?

I tried enableHighAccuracy set to false but it didn't do the trick.

GeoError happening

Hello everyone, I'm having this error which started a couple of days ago.

Have anyone gone through this error too?

fetch.js:229 GET https://geoip.nekudo.com/shutdown net::ERR_ABORTED 404

geolocator.js:957

{
  "name": "GeoError",
  "code": "UNKNOWN_ERROR",
  "message": "Could not load source at https://geoip.nekudo.com/api↵[object Event]",
  "stack": "GeoError: Could not load source at https://geoip.n…/libs/geolocator/2.1.3/geolocator.min.js:1:11824)"
}

geolocator, Cordova 4.x and up on Android

Hello,

Recently, I updated Cordova to the latest version (5.0.0) and along with it my Cordova project for an app using AngularJS and out of the blue the geolocator stopped working.

I'm aware of some new access rules for Cordova 4.x+ and I applied those to the app:

http://cordova.apache.org/docs/en/5.0.0/guide_appdev_whitelist_index.md.html#Whitelist%20Guide
https://github.com/apache/cordova-plugin-whitelist

The app is - apparently - working OK on the browser but when I build it with Cordova it doesn't work anymore (the geolocator plugin, I mean).

Peeking on the console of a device running the app, I noticed a 404 error (the geolocator plugin is sitting on the javascript.plugins.min.js file on my app among other plugins):

Failed to load resource: the server responded with a status of 404 (Not Found): https://www.google.com/jsapi?callback=geolocator.__glcb

javascript.plugins.min.js:15
GET https://www.google.com/jsapi?callback=geolocator.__glcb
m @ javascript.plugins.min.js:15
p @ javascript.plugins.min.js:16
locate @ javascript.plugins.min.js:22
(anonymous function) @ pesm-service.js:162
(anonymous function) @ angular.min.js:139
e @ angular.min.js:41
(anonymous function) @ angular.min.js:45
pesm-service.js:129 onGeoError
pesm-service.js:130 Error: Could not load source at https://www.google.com/jsapi {stack: "Error: Could not load source at https://www.google…id_asset/www/js/javascript.plugins.min.js:15:429)",message: "Could not load source at https://www.google.com/jsapi"}
message: "Could not load source at https://www.google.com/jsapi"
stack: "Error: Could not load source at https://www.google.com/jsapi↵    at Error (native)↵    at HTMLScriptElement.c.onerror (file:///android_asset/www/js/javascript.plugins.min.js:15:429)"
get stack: function () { [native code] }
set stack: function () { [native code] }
__proto__: d

But when I click on the link to the callback on the console (GET), it opens the link without a problem.

Any ideas? I'm using the latest geolocator (1.2.9).

Thank you,
Leandro

Running on a Cordova App on Android...

...I'm getting this:

GET https://www.google.com/jsapi?callback=geolocator.__glcb net::ERR_CACHE_MISS

Any ideas why? It works ok on the desktop browser.

Only via HTML5 geolocation

I tried to create HTML5 geolocation by putting the geolocator.locate() function on window.onload directly.

window.onload = function () {
                 var html5Options = { enableHighAccuracy: true, timeout: 6000, maximumAge: 0 },
                 ipFallbackIndex = chkFallback.checked ? cmbSource.selectedIndex : -1;
                 geolocator.locate(onGeoSuccess, onGeoError, 2, html5Options, 'map-canvas');
}

But there is no output, was anything wrong in it?

HTML5-Geolocation not accurate/dated

We just evaluated your (nicely implemented) script, together with some alternatives in a field test (iPhone 5, 6, 6s all running iOS 9.3.1) within an area of about 5 sq miles.

We discovered it has a known issue (that many other comparable solutions also have),
which is described in-depth and solved by a Google Cloud employee called Greg Wilson (no affiliation with him) in a Github repo of him.

Support Google Service Authentication (access_token) instead of API Key

As also mentioned in another related issue, using Google API Keys is troublesome specially when stored in a javascript file (that anyone can read).

Instead, Google suggests using a Service Account; so any server-side code is actually authenticating to Google (using a private key or certificate), receives a temporary access_token which can then be passed to the URLs when accessing Google Services.
In the Geolocator config, only a Google API Key can be specified - could this be extended to allow an access_token which will then be instead used on URLs instead of the Key=xxx parameter?

I think that would solve a lot of security issues as well as enable all Google Services to work (at least for those ready to add a server-side component for the authentication)

Cheers

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.