Using geolocation

  • Revision slug: WebAPI/Using_geolocation
  • Revision title: Using geolocation
  • Revision id: 376761
  • Created:
  • Creator: Jeremie
  • 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 to confirm 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 {
  alert("I'm sorry, but geolocation services are not supported by your browser.");
}

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 definied 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()")}} try to answer as fast as possible with a low accuracy result. It is usefull 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(), expect 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 id="submit-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 + '°, longitude is ' + longitude + '°</p>';

    var img = new Image();
    img.src = "http://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=5&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,490) }}

Browser compatibility

{{ CompatibilityTable() }}

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 5 {{CompatGeckoDesktop("1.9.1")}} 9 10.60 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 geolocation API allows the user to provide their location to web applications if they so desire. For privacy reasons, the user is asked to confirm 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 {
  alert("I'm sorry, but geolocation services are not supported by your browser.");
}
</pre>
<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 definied 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()")}} try to answer as fast as possible with a low accuracy result. It is usefull 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>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>, expect 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>Geolocation Live Example</h2>
<div class="hidden">
  <pre class="brush: css">
body { background-color:#ffffc9 }</pre>
</div>
<h3 id="HTML_Content">HTML Content</h3>
<pre class="brush: html;">
&lt;p&gt;&lt;button id="submit-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; highlight:[2,8]">
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 + '°, longitude is ' + longitude + '°&lt;/p&gt;';

    var img = new Image();
    img.src = "http://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&amp;zoom=5&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>Live Result</h3>
<p>{{ EmbedLiveSample('Geolocation_Live_Example',350,490) }}</p>
<h2 id="Browser_compatibility">Browser compatibility</h2>
<p>{{ CompatibilityTable() }}</p>
<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</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>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>
<p><!-- languages({
  "es": "es/Usar_la_Geolocalización"
}) --></p>
Revert to this revision