Using geolocation

  • Revision slug: WebAPI/Using_geolocation
  • Revision title: Using geolocation
  • Revision id: 458513
  • Created:
  • Creator: teoli
  • Is current revision? No
  • Comment

Revision Content

The geolocation API allows the user to provide their location to web applications if they so desire. For privacy reasons, the user is asked for permission to report location information.

The geolocation object

The geolocation API is published through the {{domxref("window.navigator.geolocation","navigator.geolocation")}} object.

If the object exists, geolocation services are available. You can test for the presence of geolocation thusly:

if ("geolocation" in navigator) {
  /* geolocation is available */
} else {
  /* geolocation IS NOT available */
}

Note: On Firefox 24 and older versions, "geolocation" in navigator always returned true even if the API was disabled. This has been fixed with Firefox 25 to comply with the spec. ({{ bug(884921) }}).

Getting the current position

To obtain the user's current location, you can call the {{domxref("window.navigator.geolocation.getCurrentPosition()","getCurrentPosition()")}} method. This initiates an asynchronous request to detect the user's position, and queries the positioning hardware to get up-to-date information. When the position is determined, the defined callback function is executed. You can optionally provide a second callback function to be executed if an error occurs. A third, optional, parameter is an options object where you can set the maximum age of the position returned, the time to wait for a request, and if you want high accuracy for the position.

Note: By default, {{domxref("window.navigator.geolocation.getCurrentPosition()","getCurrentPosition()")}} tries to answer as fast as possible with a low accuracy result. It is useful if you need a quick answer regardless of the accuracy. Devices with a GPS, for example, can take a minute or more to get a GPS fix, so less accurate data (IP location or wifi) may be returned to {{domxref("window.navigator.geolocation.getCurrentPosition()","getCurrentPosition()")}}.

navigator.geolocation.getCurrentPosition(function(position) {
  do_something(position.coords.latitude, position.coords.longitude);
});

The above example will cause the do_something() function to execute when the location is obtained.

Watching the current position

If the position data changes (either by device movement or if more accurate geo information arrives), you can set up a callback function that is called with that updated position information. This is done using the {{domxref("window.navigator.geolocation.watchPosition()","watchPosition()")}} function, which has the same input parameters as {{domxref("window.navigator.geolocation.getCurrentPosition()","getCurrentPosition()")}}. The callback function is called multiple times, allowing the browser to either update your location as you move, or provide a more accurate location as different techniques are used to geolocate you. The error callback function, which is optional just as it is for {{domxref("window.navigator.geolocation.getCurrentPosition()","getCurrentPosition()")}}, is called only once, if there will never be valid results returned.

Note: You can use {{domxref("window.navigator.geolocation.watchPosition()","watchPosition()")}} without an initial {{domxref("window.navigator.geolocation.getCurrentPosition()","getCurrentPosition()")}} call.

var watchID = navigator.geolocation.watchPosition(function(position) {
  do_something(position.coords.latitude, position.coords.longitude);
});

The {{domxref("window.navigator.geolocation.watchPosition()","watchPosition()")}} method returns an ID number that can be used to uniquely identify the requested position watcher; you use this value in tandem with the {{domxref("window.navigator.geolocation.clearWatch()","clearPosition()")}} method to stop watching the user's location.

navigator.geolocation.clearWatch(watchID);

Fine tuning reponse

Both {{domxref("window.navigator.geolocation.getCurrentPosition()","getCurrentPosition()")}} and {{domxref("window.navigator.geolocation.watchPosition()","watchPosition()")}} accept a success callback, an optional error callback, and an optional PositionOptions object.

{{page("/en-US/docs/DOM/window.navigator.geolocation.getCurrentPosition","PositionOptions")}}

A call to {{domxref("window.navigator.geolocation.watchPosition()","watchPosition")}} could look like:

function geo_success(position) {
  do_something(position.coords.latitude, position.coords.longitude);
}

function geo_error() {
  alert("Sorry, no position available.");
}

var geo_options = {
  enableHighAccuracy: true, 
  maximumAge        : 30000, 
  timeout           : 27000
};

var wpid = navigator.geolocation.watchPosition(geo_success, geo_error, geo_options);

A demo of watchPosition in use: http://www.thedotproduct.org/experiments/geo/


Describing a position

The user's location is described using a Position object referencing a Coordinates object.

{{page("/en-US/docs/DOM/window.navigator.geolocation.getCurrentPosition","Position")}}

{{page("/en-US/docs/DOM/window.navigator.geolocation.getCurrentPosition","Coordinates")}}

Handling errors

The error callback function, if provided when calling getCurrentPosition() or watchPosition(), expects a PositionError object as its first parameter.

function errorCallback(error) {
  alert('ERROR(' + error.code + '): ' + error.message);
};

{{page("/en-US/docs/DOM/window.navigator.geolocation.getCurrentPosition","PositionError")}}

Geolocation Live Example

HTML Content

<p><button onclick="geoFindMe()">Show my location</button></p>
<div id="out"></div>

JavaScript Content

function geoFindMe() {
  var output = document.getElementById("out");

  if (!navigator.geolocation){
    output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
    return;
  }

  function success(position) {
    var latitude  = position.coords.latitude;
    var longitude = position.coords.longitude;

    output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';

    var img = new Image();
    img.src = "http://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=13&size=300x300&sensor=false";

    output.appendChild(img);
  };

  function error() {
    output.innerHTML = "Unable to retrieve your location";
  };

  output.innerHTML = "<p>Locating…</p>";

  navigator.geolocation.getCurrentPosition(success, error);
}

Live Result

{{ EmbedLiveSample('Geolocation_Live_Example',350,410) }}

Prompting for permission

Any add-on hosted on addons.mozilla.org which makes use of geolocation data must explicitly request permission before doing so. The following function will request permission in a manner similar to the automatic prompt displayed for web pages. The user's response will be saved in the preference specified by the pref parameter, if applicable. The function provided in the callback parameter will be called with a boolean value indicating the user's response. If true, the add-on may access geolocation data.

function prompt(window, pref, message, callback) {
    let branch = Components.classes["@mozilla.org/preferences-service;1"]
                           .getService(Components.interfaces.nsIPrefBranch);

    if (branch.getPrefType(pref) === branch.PREF_STRING) {
        switch (branch.getCharPref(pref)) {
        case "always":
            return callback(true);
        case "never":
            return callback(false);
        }
    }

    let done = false;

    function remember(value, result) {
        return function() {
            done = true;
            branch.setCharPref(pref, value);
            callback(result);
        }
    }

    let self = window.PopupNotifications.show(
        window.gBrowser.selectedBrowser,
        "geolocation",
        message,
        "geo-notification-icon",
        {
            label: "Share Location",
            accessKey: "S",
            callback: function(notification) {
                done = true;
                callback(true);
            }
        }, [
            {
                label: "Always Share",
                accessKey: "A",
                callback: remember("always", true)
            },
            {
                label: "Never Share",
                accessKey: "N",
                callback: remember("never", false)
            }
        ], {
            eventCallback: function(event) {
                if (event === "dismissed") {
                    if (!done) callback(false);
                    done = true;
                    window.PopupNotifications.remove(self);
                }
            },
            persistWhileVisible: true
        });
}

prompt(window,
       "extensions.foo-addon.allowGeolocation",
       "Foo Add-on wants to know your location.",
       function callback(allowed) { alert(allowed); });

Browser compatibility

{{ CompatibilityTable() }}
 
Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 5 {{CompatGeckoDesktop("1.9.1")}} 9 10.60
Removed in 15.0
Reintroduced in 16.0
5
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support {{CompatUnknown()}} {{CompatUnknown()}} {{CompatGeckoMobile("4")}} {{CompatUnknown()}} 10.60 {{CompatUnknown()}}

Gecko notes

Firefox includes support for locating you based on your WiFi information using Google Location Services. In the transaction between Firefox and Google, data is exchanged including WiFi Access Point data, an access token (similar to a 2 week cookie), and the user's IP address. For more information, please check out Mozilla's Privacy Policy and Google's Privacy Policy covering how this data can be used.

Firefox 3.6 (Gecko 1.9.2) added support for using the GPSD (GPS daemon) service for geolocation on Linux.

See also

Revision Source

<p>The <strong>geolocation API</strong> allows the user to provide their location to web applications if they so desire. For privacy reasons, the user is asked for permission to report location information.</p>
<h2 id="The_geolocation_object">The geolocation object</h2>
<p>The geolocation API is published through the {{domxref("window.navigator.geolocation","navigator.geolocation")}} object.</p>
<p>If the object exists, geolocation services are available. You can test for the presence of geolocation thusly:</p>
<pre class="brush: js">
if ("geolocation" in navigator) {
  /* geolocation is available */
} else {
  /* geolocation IS NOT available */
}
</pre>
<div class="note">
  <p><strong>Note:</strong> On Firefox&nbsp;24 and older versions, <code>"geolocation" in navigator</code> always returned <code>true</code> even if the API was disabled. This has been fixed with <a href="/en-US/docs/Mozilla/Firefox/Releases/25/Site_Compatibility">Firefox&nbsp;25</a> to comply with the spec. ({{ bug(884921) }}).</p>
</div>
<h3 id="Getting_the_current_position">Getting the current position</h3>
<p>To obtain the user's current location, you can call the {{domxref("window.navigator.geolocation.getCurrentPosition()","getCurrentPosition()")}} method. This initiates an asynchronous request to detect the user's position, and queries the positioning hardware to get up-to-date information. When the position is determined, the defined callback function is executed. You can optionally provide a second callback function to be executed if an error occurs. A third, optional, parameter is an options object where you can set the maximum age of the position returned, the time to wait for a request, and if you want high accuracy for the position.</p>
<div class="note">
  <p><strong>Note:</strong> By default, {{domxref("window.navigator.geolocation.getCurrentPosition()","getCurrentPosition()")}} tries to answer as fast as possible with a low accuracy result. It is useful if you need a quick answer regardless of the accuracy. Devices with a GPS, for example, can take a minute or more to get a GPS fix, so less accurate data (IP location or wifi) may be returned to {{domxref("window.navigator.geolocation.getCurrentPosition()","getCurrentPosition()")}}.</p>
</div>
<pre class="brush: js">
navigator.geolocation.getCurrentPosition(function(position) {
  do_something(position.coords.latitude, position.coords.longitude);
});</pre>
<p>The above example will cause the <code>do_something()</code> function to execute when the location is obtained.</p>
<h3 id="Watching_the_current_position">Watching the current position</h3>
<p>If the position data changes (either by device movement or if more accurate geo information arrives), you can set up a callback function that is called with that updated position information. This is done using the {{domxref("window.navigator.geolocation.watchPosition()","watchPosition()")}} function, which has the same input parameters as {{domxref("window.navigator.geolocation.getCurrentPosition()","getCurrentPosition()")}}. The callback function is called multiple times, allowing the browser to either update your location as you move, or provide a more accurate location as different techniques are used to geolocate you. The error callback function, which is optional just as it is for {{domxref("window.navigator.geolocation.getCurrentPosition()","getCurrentPosition()")}}, is called only once, if there will never be valid results returned.</p>
<div class="note">
  <p><strong>Note:</strong> You can use {{domxref("window.navigator.geolocation.watchPosition()","watchPosition()")}} without an initial {{domxref("window.navigator.geolocation.getCurrentPosition()","getCurrentPosition()")}} call.</p>
</div>
<pre class="brush: js">
var watchID = navigator.geolocation.watchPosition(function(position) {
  do_something(position.coords.latitude, position.coords.longitude);
});</pre>
<p>The {{domxref("window.navigator.geolocation.watchPosition()","watchPosition()")}} method returns an ID number that can be used to uniquely identify the requested position watcher; you use this value in tandem with the {{domxref("window.navigator.geolocation.clearWatch()","clearPosition()")}} method to stop watching the user's location.</p>
<pre class="brush: js">
navigator.geolocation.clearWatch(watchID);
</pre>
<h3 id="Fine_tuning_reponse">Fine tuning reponse</h3>
<p>Both {{domxref("window.navigator.geolocation.getCurrentPosition()","getCurrentPosition()")}} and {{domxref("window.navigator.geolocation.watchPosition()","watchPosition()")}} accept a success callback, an optional error callback, and an optional <code>PositionOptions</code> object.</p>
<p>{{page("/en-US/docs/DOM/window.navigator.geolocation.getCurrentPosition","PositionOptions")}}</p>
<p>A call to {{domxref("window.navigator.geolocation.watchPosition()","watchPosition")}} could look like:</p>
<pre class="brush: js">
function geo_success(position) {
  do_something(position.coords.latitude, position.coords.longitude);
}

function geo_error() {
  alert("Sorry, no position available.");
}

var geo_options = {
  enableHighAccuracy: true, 
  maximumAge        : 30000, 
  timeout           : 27000
};

var wpid = navigator.geolocation.watchPosition(geo_success, geo_error, geo_options);</pre>
<p><a id="fck_paste_padding">A demo of watchPosition in use: </a><a class="external" href="http://www.thedotproduct.org/experiments/geo/">http://www.thedotproduct.org/experiments/geo/</a><br />
  <a id="fck_paste_padding"></a></p>
<h2 id="Describing_a_position">Describing a position</h2>
<p>The user's location is described using a <code>Position</code> object referencing a <code>Coordinates</code> object.</p>
<p>{{page("/en-US/docs/DOM/window.navigator.geolocation.getCurrentPosition","Position")}}</p>
<p>{{page("/en-US/docs/DOM/window.navigator.geolocation.getCurrentPosition","Coordinates")}}</p>
<h2 id="Handling_errors">Handling errors</h2>
<p>The error callback function, if provided when calling <code>getCurrentPosition()</code> or <code>watchPosition()</code>, expects a <code>PositionError</code> object as its first parameter.</p>
<pre class="brush: js">
function errorCallback(error) {
  alert('ERROR(' + error.code + '): ' + error.message);
};
</pre>
<p>{{page("/en-US/docs/DOM/window.navigator.geolocation.getCurrentPosition","PositionError")}}</p>
<h2 id="Geolocation_Live_Example">Geolocation Live Example</h2>
<div class="hidden">
  <pre class="brush: css">
body {
  padding: 20px;
  background-color:#ffffc9
}

p { margin : 0; }
</pre>
</div>
<h3 id="HTML_Content">HTML Content</h3>
<pre class="brush: html;">
&lt;p&gt;&lt;button onclick="geoFindMe()"&gt;Show my location&lt;/button&gt;&lt;/p&gt;
&lt;div id="out"&gt;&lt;/div&gt;
</pre>
<h3 id="JavaScript_Content">JavaScript Content</h3>
<pre class="brush: js;">
function geoFindMe() {
  var output = document.getElementById("out");

  if (!navigator.geolocation){
    output.innerHTML = "&lt;p&gt;Geolocation is not supported by your browser&lt;/p&gt;";
    return;
  }

  function success(position) {
    var latitude  = position.coords.latitude;
    var longitude = position.coords.longitude;

    output.innerHTML = '&lt;p&gt;Latitude is ' + latitude + '° &lt;br&gt;Longitude is ' + longitude + '°&lt;/p&gt;';

    var img = new Image();
    img.src = "http://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&amp;zoom=13&amp;size=300x300&amp;sensor=false";

    output.appendChild(img);
  };

  function error() {
    output.innerHTML = "Unable to retrieve your location";
  };

  output.innerHTML = "&lt;p&gt;Locating…&lt;/p&gt;";

  navigator.geolocation.getCurrentPosition(success, error);
}
</pre>
<h3 id="Live_Result">Live Result</h3>
<p>{{ EmbedLiveSample('Geolocation_Live_Example',350,410) }}</p>
<h2 id="Prompting_for_permission">Prompting for permission</h2>
<p>Any add-on hosted on addons.mozilla.org which makes use of geolocation data must explicitly request permission before doing so. The following function will request permission in a manner similar to the automatic prompt displayed for web pages. The user's response will be saved in the preference specified by the <code>pref</code> parameter, if applicable. The function provided in the <code>callback</code> parameter will be called with a boolean value indicating the user's response. If <code>true</code>, the add-on may access geolocation data.</p>
<pre class="brush: js">
function prompt(window, pref, message, callback) {
    let branch = Components.classes["@mozilla.org/preferences-service;1"]
                           .getService(Components.interfaces.nsIPrefBranch);

    if (branch.getPrefType(pref) === branch.PREF_STRING) {
        switch (branch.getCharPref(pref)) {
        case "always":
            return callback(true);
        case "never":
            return callback(false);
        }
    }

    let done = false;

    function remember(value, result) {
        return function() {
            done = true;
            branch.setCharPref(pref, value);
            callback(result);
        }
    }

    let self = window.PopupNotifications.show(
        window.gBrowser.selectedBrowser,
        "geolocation",
        message,
        "geo-notification-icon",
        {
            label: "Share Location",
            accessKey: "S",
            callback: function(notification) {
                done = true;
                callback(true);
            }
        }, [
            {
                label: "Always Share",
                accessKey: "A",
                callback: remember("always", true)
            },
            {
                label: "Never Share",
                accessKey: "N",
                callback: remember("never", false)
            }
        ], {
            eventCallback: function(event) {
                if (event === "dismissed") {
                    if (!done) callback(false);
                    done = true;
                    window.PopupNotifications.remove(self);
                }
            },
            persistWhileVisible: true
        });
}

prompt(window,
       "extensions.foo-addon.allowGeolocation",
       "Foo Add-on wants to know your location.",
       function callback(allowed) { alert(allowed); });
</pre>
<h2 id="Browser_compatibility">Browser compatibility</h2>
<div>
  {{ CompatibilityTable() }}</div>
<div>
  &nbsp;</div>
<div id="compat-desktop">
  <table class="compat-table">
    <tbody>
      <tr>
        <th>Feature</th>
        <th>Chrome</th>
        <th>Firefox (Gecko)</th>
        <th>Internet Explorer</th>
        <th>Opera</th>
        <th>Safari</th>
      </tr>
      <tr>
        <td>Basic support</td>
        <td>5</td>
        <td>{{CompatGeckoDesktop("1.9.1")}}</td>
        <td>9</td>
        <td>10.60<br />
          Removed in 15.0<br />
          Reintroduced in 16.0</td>
        <td>5</td>
      </tr>
    </tbody>
  </table>
</div>
<div id="compat-mobile">
  <table class="compat-table">
    <tbody>
      <tr>
        <th>Feature</th>
        <th>Android</th>
        <th>Chrome for Android</th>
        <th>Firefox Mobile (Gecko)</th>
        <th>IE Mobile</th>
        <th>Opera Mobile</th>
        <th>Safari Mobile</th>
      </tr>
      <tr>
        <td>Basic support</td>
        <td>{{CompatUnknown()}}</td>
        <td>{{CompatUnknown()}}</td>
        <td>{{CompatGeckoMobile("4")}}</td>
        <td>{{CompatUnknown()}}</td>
        <td>10.60</td>
        <td>{{CompatUnknown()}}</td>
      </tr>
    </tbody>
  </table>
</div>
<h3 id="Gecko_notes">Gecko notes</h3>
<p>Firefox includes support for locating you based on your WiFi information using Google Location Services. In the transaction between Firefox and Google, data is exchanged including WiFi Access Point data, an access token (similar to a 2 week cookie), and the user's IP address. For more information, please check out Mozilla's <a class="external" href="http://www.mozilla.com/en-US/legal/privacy/" title="http://www.mozilla.com/en-US/legal/privacy/">Privacy Policy</a> and Google's <a class="external" href="http://www.google.com/privacy-lsf.html" title="http://www.google.com/privacy-lsf.html">Privacy Policy</a> covering how this data can be used.</p>
<p>Firefox 3.6 (Gecko 1.9.2) added support for using the <a class="external" href="http://catb.org/gpsd/" title="http://catb.org/gpsd/">GPSD</a> (GPS daemon) service for geolocation on Linux.</p>
<h2 id="See_also">See also</h2>
<ul>
  <li>{{domxref("window.navigator.geolocation","navigator.geolocation")}}</li>
  <li><a href="http://www.w3.org/TR/geolocation-API/" rel="external" title="http://www.w3.org/TR/geolocation-API/">Geolocation API on w3.org</a></li>
  <li><a href="/en-US/demos/tag/tech:geolocation" title="en-US/demos/tag/tech:geolocation/">Demos about the Geolocation API</a></li>
</ul>
Revert to this revision