Pick up Current Location by Google Maps and enter the address in a form

Asked

Viewed 4,865 times

1

I am learning how to work with the google maps API, and would like to know how to pick up the current user location and enter the address in a form. There’s little you can do so far. Could you help me with that.

function init () {
				loadPosition();
			}

			function loadPosition(){
				if(navigator.geolocation){
					document.getElementById("status").innerHTML = "Seu navegador suporta HTML5!";

					navigator.geolocation.getCurrentPosition(funcaoSucesso,funcaoErro);
				}
			}

			function funcaoSucesso(posicao){
				var latitude = posicao.coords.latitude;
				var longitude = posicao.coords.longitude;
				

				if(!latitude || !longitude){
					document.getElementById("status").innerHTML = "Não foi possível consultar sua localização!"
				}

 
			}

			function funcaoErro(error){
				switch(error){
					case 0:
						alert("Erro ao atualizar a sua posição. Erro:"+error.message);
					break;
					case 1:
						alert("O usuário não compartilhou sua localização.");
					break;
					case 2:
						alert("O browser não está habilitado para localização.");
					break;
					case 3:
						alert("Tempo de requisição esgotado. [TIMEOUT]");
					break;
				}
			}

  • I didn’t understand very well. You want to enter the address based on latitude and longitude?

  • Yes, street, city and state.

1 answer

1

The consumption of the following URL below, returns exactly one json. So you can interpret it and fill out your interest form, whichever way you prefer. See:

http://maps.googleapis.com/maps/api/geocode/json?latlng=44.4647452,7.3553838&sensor=true

Code ready

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Reverse Geocoding</title>
    <style>
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #map {
        height: 100%;
      }
#floating-panel {
  position: absolute;
  top: 10px;
  left: 25%;
  z-index: 5;
  background-color: #fff;
  padding: 5px;
  border: 1px solid #999;
  text-align: center;
  font-family: 'Roboto','sans-serif';
  line-height: 30px;
  padding-left: 10px;
}

    </style>
    <style>
      #floating-panel {
        position: absolute;
        top: 5px;
        left: 50%;
        margin-left: -180px;
        width: 350px;
        z-index: 5;
        background-color: #fff;
        padding: 5px;
        border: 1px solid #999;
      }
      #latlng {
        width: 225px;
      }
    </style>
  </head>
  <body>
    <div id="floating-panel">
      <input id="latlng" type="text" value="-23.584667,-46.660441">
      <input id="submit" type="button" value="Reverse Geocode">
    </div>
    <div id="map"></div>
    <script>
function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 8,
    center: {lat: -23.584667, lng: -46.660441}
  });
  var geocoder = new google.maps.Geocoder;
  var infowindow = new google.maps.InfoWindow;

  document.getElementById('submit').addEventListener('click', function() {
    geocodeLatLng(geocoder, map, infowindow);
  });
}

function geocodeLatLng(geocoder, map, infowindow) {
  var input = document.getElementById('latlng').value;
  var latlngStr = input.split(',', 2);
  var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
  geocoder.geocode({'location': latlng}, function(results, status) {
    if (status === google.maps.GeocoderStatus.OK) {
      if (results[1]) {
        map.setZoom(11);
        var marker = new google.maps.Marker({
          position: latlng,
          map: map
        });
        infowindow.setContent(results[1].formatted_address);
        infowindow.open(map, marker);
      } else {
        window.alert('No results found');
      }
    } else {
      window.alert('Geocoder failed due to: ' + status);
    }
  });
}

    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAIV86zJW6FGDHyqHhQndiRSbtH1DTJ8DM&signed_in=true&callback=initMap"
        async defer></script>
  </body>
</html>

Take a look at Reverse Geocoding referring to the Google documentation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.