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
|
---
title: API de Geolocalização
slug: Web/API/Geolocation/Utilizacao_da_geolocalizacao
tags:
- API de Geolocalização
- Guía
- Intermediário
translation_of: Web/API/Geolocation_API
---
<p>{{securecontext_header}}{{APIRef("Geolocation API")}}</p>
<p>A <strong>API de geolocalização </strong>permite que o utilizador forneça a sua localização nas aplicações da Web, se assim o desejar. Por motivos de segurança, é solicitado ao utilizador para dar permissão para informar a informação da localização.</p>
<h2 id="O_objeto_de_geolocalização">O objeto de geolocalização</h2>
<p>A API de <a href="/pt-PT/docs/Web/API/Geolocation">Geolocation</a> é publicada através do objeto {{domxref("navigator.geolocation")}}.</p>
<p>Se o objeto existir, os serviços de geolocalização estarão disponíveis. Pode testar a presença de geolocalização assim:</p>
<pre class="brush: js">if ("geolocation" in navigator) {
/* geolocation is available */
} else {
/* geolocation IS NOT available */
}
</pre>
<div class="note">
<p><strong>Nota:</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="Obter_a_posição_atual">Obter a posição atual</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>Nota:</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="Vigiar_a_posição_atual">Vigiar a posição atual</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>Nota:</strong> pode utilizar {{domxref("Geolocation.watchPosition()","watchPosition()")}} sem uma chamada inicial {{domxref("Geolocation.getCurrentPosition()","getCurrentPosition()")}}.</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="Resposta_de_ajuste_preciso">Resposta de ajuste preciso</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>
<h2 id="Descrever_uma_posição">Descrever uma posição</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="Lidar_com_erros">Lidar com erros</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="Exemplo_de_Geolocalização_Live">Exemplo de Geolocalização <em>Live</em></h2>
<div class="hidden">
<pre class="brush: css">body {
padding: 20px;
background-color:#ffffc9
}
p { margin : 0; }
</pre>
</div>
<h3 id="Conteúdo_HTML">Conteúdo HTML</h3>
<pre class="brush: html;"><p><button onclick="geoFindMe()">Show my location</button></p>
<div id="out"></div>
</pre>
<h3 id="Conteúdo_JavaScript">Conteúdo JavaScript</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="Resultado_Live">Resultado <em>Live</em></h3>
<p>{{EmbedLiveSample('Geolocation_Live_Example', 350, 410)}}</p>
<h2 id="Aviso_para_permissão">Aviso para permissão</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="Compatibilidade_de_navegador">Compatibilidade de navegador</h2>
<p>{{Compat("api.Geolocation")}}</p>
<h3 id="Disponibilidade">Disponibilidade</h3>
<p>Como a localização baseada em Wi-Fi é geralmente fornecida pelo Google, a API de Geolocalização "vanilla" pode estar indisponível na China. Pode utilizar os provedores locais de terceiros, tais como <a href="http://lbsyun.baidu.com/index.php?title=jspopular/guide/geolocation">Baidu</a>, <a href="https://lbs.amap.com/api/javascript-api/guide/services/geolocation#geolocation">Autonavi</a>, ou <a href="http://lbs.qq.com/tool/component-geolocation.html">Tencent</a>. Estes serviços utilziam o endereço de IP do utilizador e/ou uma aplicação local para fornecer o posicionamento melhorado.</p>
<h2 id="Consulte_também">Consulte também</h2>
<ul>
<li>{{domxref("navigator.geolocation")}}</li>
<li><a href="https://developer.mozilla.org/pt-PT/docs/Web/Apps/Fundamentals/gather_and_modify_data/Plotting_yourself_on_the_map">Localizar-se no mapa</a></li>
<li><a href="https://www.w3.org/TR/geolocation-API/" rel="external">API de Geolocation em w3.org</a></li>
<li><a href="https://hacks.mozilla.org/2013/10/who-moved-my-geolocation/">Quem moveu a minha geolocalização?</a> (Blogue de <em>Hacks</em>)</li>
</ul>
|