Visão geral
Neste tutorial, abordamos como mostrar a localização geográfica de um usuário ou dispositivo em um mapa do Google usando o recurso de geolocalização HTML5 do navegador e a API Maps JavaScript. A localização geográfica de um usuário só vai aparecer se ele tiver permitido o Compartilhamento de local.
Abaixo está um mapa que pode identificar seu local atual.
O exemplo abaixo mostra o código inteiro para criar esse mapa.
TypeScript
// Note: This example requires that you consent to location sharing when // prompted by your browser. If you see the error "The Geolocation service // failed.", it means you probably did not give permission for the browser to // locate you. let map: google.maps.Map, infoWindow: google.maps.InfoWindow; function initMap(): void { map = new google.maps.Map(document.getElementById("map") as HTMLElement, { center: { lat: -34.397, lng: 150.644 }, zoom: 6, }); infoWindow = new google.maps.InfoWindow(); const locationButton = document.createElement("button"); locationButton.textContent = "Pan to Current Location"; locationButton.classList.add("custom-map-control-button"); map.controls[google.maps.ControlPosition.TOP_CENTER].push(locationButton); locationButton.addEventListener("click", () => { // Try HTML5 geolocation. if (navigator.geolocation) { navigator.geolocation.getCurrentPosition( (position: GeolocationPosition) => { const pos = { lat: position.coords.latitude, lng: position.coords.longitude, }; infoWindow.setPosition(pos); infoWindow.setContent("Location found."); infoWindow.open(map); map.setCenter(pos); }, () => { handleLocationError(true, infoWindow, map.getCenter()!); } ); } else { // Browser doesn't support Geolocation handleLocationError(false, infoWindow, map.getCenter()!); } }); } function handleLocationError( browserHasGeolocation: boolean, infoWindow: google.maps.InfoWindow, pos: google.maps.LatLng ) { infoWindow.setPosition(pos); infoWindow.setContent( browserHasGeolocation ? "Error: The Geolocation service failed." : "Error: Your browser doesn't support geolocation." ); infoWindow.open(map); } declare global { interface Window { initMap: () => void; } } window.initMap = initMap;
JavaScript
// Note: This example requires that you consent to location sharing when // prompted by your browser. If you see the error "The Geolocation service // failed.", it means you probably did not give permission for the browser to // locate you. let map, infoWindow; function initMap() { map = new google.maps.Map(document.getElementById("map"), { center: { lat: -34.397, lng: 150.644 }, zoom: 6, }); infoWindow = new google.maps.InfoWindow(); const locationButton = document.createElement("button"); locationButton.textContent = "Pan to Current Location"; locationButton.classList.add("custom-map-control-button"); map.controls[google.maps.ControlPosition.TOP_CENTER].push(locationButton); locationButton.addEventListener("click", () => { // Try HTML5 geolocation. if (navigator.geolocation) { navigator.geolocation.getCurrentPosition( (position) => { const pos = { lat: position.coords.latitude, lng: position.coords.longitude, }; infoWindow.setPosition(pos); infoWindow.setContent("Location found."); infoWindow.open(map); map.setCenter(pos); }, () => { handleLocationError(true, infoWindow, map.getCenter()); } ); } else { // Browser doesn't support Geolocation handleLocationError(false, infoWindow, map.getCenter()); } }); } function handleLocationError(browserHasGeolocation, infoWindow, pos) { infoWindow.setPosition(pos); infoWindow.setContent( browserHasGeolocation ? "Error: The Geolocation service failed." : "Error: Your browser doesn't support geolocation." ); infoWindow.open(map); } window.initMap = initMap;
Testar amostra
O que é geolocalização?
Geolocalização se refere à identificação do local geográfico de um usuário ou dispositivo de computação via vários mecanismos de coleta de dados. Normalmente, a maior parte dos serviços de geolocalização usa endereços de roteamento de rede ou dispositivos internos de GPS para determinar esse local. A geolocalização é uma API específica do dispositivo. Isso significa que navegadores ou dispositivos precisam ser compatíveis com geolocalização para usar esse recurso em aplicativos da Web.
Padrão de geolocalização W3C
Para realizar a geolocalização, os aplicativos precisam ser compatíveis com o padrão de geolocalização W3C. O exemplo de código acima determina a localização do usuário com a propriedade navigator.geolocation
do W3C.
Alguns navegadores usam endereços IP para detectar o local de um usuário. No entanto, talvez só mostrem uma estimativa aproximada dele. A abordagem W3C é a mais fácil e com maior suporte, portanto, ela deve ter prioridade sobre outros métodos de geolocalização.