diff options
author | Florian Merz <me@fiji-flo.de> | 2021-02-11 14:50:24 +0100 |
---|---|---|
committer | Florian Merz <me@fiji-flo.de> | 2021-02-11 14:50:24 +0100 |
commit | 2c2df5ea01eb5cd8b9ea226b2869337e59c5fe3e (patch) | |
tree | 86ab4534d10092b293d4b7ab169fe1a8a2421bfa /files/pt-pt/web/api/geolocation_api | |
parent | 8260a606c143e6b55a467edf017a56bdcd6cba7e (diff) | |
download | translated-content-2c2df5ea01eb5cd8b9ea226b2869337e59c5fe3e.tar.gz translated-content-2c2df5ea01eb5cd8b9ea226b2869337e59c5fe3e.tar.bz2 translated-content-2c2df5ea01eb5cd8b9ea226b2869337e59c5fe3e.zip |
unslug pt-pt: move
Diffstat (limited to 'files/pt-pt/web/api/geolocation_api')
-rw-r--r-- | files/pt-pt/web/api/geolocation_api/index.html | 242 |
1 files changed, 242 insertions, 0 deletions
diff --git a/files/pt-pt/web/api/geolocation_api/index.html b/files/pt-pt/web/api/geolocation_api/index.html new file mode 100644 index 0000000000..40fb7ce571 --- /dev/null +++ b/files/pt-pt/web/api/geolocation_api/index.html @@ -0,0 +1,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> |