1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
|
---
title: Using geolocation
slug: Web/API/Geolocation_API
translation_of: Web/API/Geolocation_API
original_slug: Web/API/Geolocation/Using_geolocation
---
<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("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 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 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("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("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("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("Geolocation.watchPosition()","watchPosition()")}} function, which has the same input parameters as {{domxref("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("Geolocation.getCurrentPosition()","getCurrentPosition()")}}, can be called repeatedly.</p>
<div class="note">
<p><strong>Note:</strong> You can use {{domxref("Geolocation.watchPosition()","watchPosition()")}} without an initial {{domxref("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("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("Geolocation.clearWatch()","clearWatch()")}} method to stop watching the user's location.</p>
<pre class="brush: js">navigator.geolocation.clearWatch(watchID);
</pre>
<h3 id="Fine_tuning_response">Fine tuning response</h3>
<p>Both {{domxref("Geolocation.getCurrentPosition()","getCurrentPosition()")}} and {{domxref("Geolocation.watchPosition()","watchPosition()")}} accept a success callback, an optional error callback, and an optional <a href="/en-US/docs/Web/API/PositionOptions">PositionOptions</a> object.</p>
<p>{{page("/en-US/docs/DOM/navigator.geolocation.getCurrentPosition","PositionOptions")}}</p>
<p>A call to {{domxref("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 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/navigator/geolocation/getCurrentPosition","Position")}}</p>
<p>{{page("/en-US/docs/DOM/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 <a href="/en-US/docs/Web/API/PositionError">PositionError</a> 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/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;"><p><button onclick="geoFindMe()">Show my location</button></p>
<div id="out"></div>
</pre>
<h3 id="JavaScript_Content">JavaScript Content</h3>
<pre class="brush: js;">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 = "https://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);
}
</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 <a href="https://addons.mozilla.org/">addons.mozilla.org</a> 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 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")}}<sup>[1]</sup></td>
<td>9</td>
<td>10.60<br>
{{CompatNo}} 15.0<br>
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>Firefox OS</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>1.0.1</td>
<td>{{CompatUnknown}}</td>
<td>10.60<br>
{{CompatNo}} 15.0<br>
16.0</td>
<td>{{CompatUnknown}}</td>
</tr>
</tbody>
</table>
</div>
<p>[1] 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 href="http://www.mozilla.com/en-US/legal/privacy/">Privacy Policy</a> and Google's <a href="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 href="http://catb.org/gpsd/">GPSD</a> (GPS daemon) service for geolocation on Linux.</p>
<h2 id="See_also">See also</h2>
<ul>
<li>{{domxref("navigator.geolocation")}}</li>
<li><a href="/en-US/Apps/Build/gather_and_modify_data/Plotting_yourself_on_the_map">Plotting yourself on the map</a></li>
<li><a href="http://www.w3.org/TR/geolocation-API/" rel="external">Geolocation API on w3.org</a></li>
<li><a href="/en-US/demos/tag/tech:geolocation">Demos about the Geolocation API</a></li>
<li><a href="https://hacks.mozilla.org/2013/10/who-moved-my-geolocation/">Who moved my geolocation?</a> (Hacks blog)</li>
</ul>
|