En este post aprenderemos cómo obtener una dirección formateada con latitud y longitud después de dar click en el mapa, además usaremos un marcador para ilustrar el punto seleccionado en el mapa
Manos a la obra
Comenzaremos definiendo los imputs donde mostraremos cada información. Crearemos un div con el id ="mapa". Ahí se visualizará nuestro mapa.
<div id="Mapa" width="100%" style="height: 280px;"></div> <input type="text" name="input-address-formated" id="input-address-formated"> <input type="text" name="input-address" id="input-address"> <input type="text" name="input-city" id="input-city"> <input type="text" name="input-country" id="input-country"> <input type="text" name="input-postal-code" id="input-postal-code"> <input type="text" name="input-street" id="input-street"> <input type="text" name="input-exterior-number" id="input-exterior-number"> <input type="text" name="latitude" id="latitude"> <input type="text" name="longitude" id="longitude">
Como segundo paso debemos importar el script de Jquery y Maps
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"> </script> <script src="https://maps.googleapis.com/maps/api/js?key=Aqui_va_tu_key"> </script>
Posteriormente inicializaremos nuestras configuraciones para el mapa :
var map; var myLatlng = new google.maps.LatLng(16.79950392066451, -99.80640426685476); var geocoder = new google.maps.Geocoder(); function initialize() { var mapOptions = { zoom: 13, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP };
Agregaremos un listener para escuchar cada vez que se ejecute el evento click en el mapa y en el una función que se encargará de mover el marcador y traer información (Longitud, latitud, direcciones).
google.maps.event.addListener(map, 'click', function(event) { placeMarker(event.latLng); });
La función "placeMarker contendrá lo siguiente:
function placeMarker(location) { if (marker == null) { marker = new google.maps.Marker({ position: location, map: map, zoom:13 }); } else { marker.setPosition(location); } geocoder.geocode( { location: location }, ( results = google.maps.GeocoderResult, status= google.maps.GeocoderStatus ) => { if (status === "OK") { if (results[0]) { console.log (results[0].address_components); var address_components = results[0].address_components; var components={}; jQuery.each(address_components,function(k,v1) {jQuery.each(v1.types,function(k2, v2){components[v2]=v1.long_name});}); var city, postal_code,state,country,sublocality,street_number,route; console.log(components); if(components.locality) { city = components.locality; } if(!city) { city = components.administrative_area_level_1; } if(components.postal_code) { postal_code = components.postal_code; } if(components.postal_code) { postal_code = components.postal_code; } if(components.administrative_area_level_1) { state = components.administrative_area_level_1; } if(components.route) { route = components.route; } if(components.sublocality_level_1) { sublocality = components.sublocality_level_1; } if(components.country) { country = components.country; } if(components.street_number) { street_number = components.street_number; } $('#input-address-formated').val(results[0].formatted_address); $('#input-address').val(state); $('#input-city').val(city); $('#input-country').val(country); $('#input-postal-code').val(postal_code); $('#input-street').val(route+', '+sublocality); $('#input-interior-number').val(street_number); $('#input-exterior-number').val(street_number); $('#latitude').val(marker.getPosition().lat()); $('#longitude').val(marker.getPosition().lng()); } else { window.alert("No results found"); } } else { window.alert("Geocoder failed due to: " + status); } } ); }
La información que contiene la respuesta de google maps la puedes ver en consola (En caso de que neceistes alguna información adicional a la que incluye este post):
Por ultimo, solo nos queda inicializar nuestro mapa y ¡listo!
google.maps.event.addDomListener(window, 'load', initialize);
Vista previa
Les dejo el código completo:
<div id="Mapa" width="100%" style="height: 280px;"></div> <input type="text" name="input-address-formated" id="input-address-formated"> <input type="text" name="input-address" id="input-address"> <input type="text" name="input-city" id="input-city"> <input type="text" name="input-country" id="input-country"> <input type="text" name="input-postal-code" id="input-postal-code"> <input type="text" name="input-street" id="input-street"> <input type="text" name="input-exterior-number" id="input-exterior-number"> <input type="text" name="latitude" id="latitude"> <input type="text" name="longitude" id="longitude"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"> </script> <script src="https://maps.googleapis.com/maps/api/js?key=tu_api_key"> </script> <script type="application/javascript"> var map; var marker; var myLatlng = new google.maps.LatLng(16.79950392066451, -99.80640426685476); var geocoder = new google.maps.Geocoder(); function initialize() { var mapOptions = { zoom: 13, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById("Mapa"), mapOptions); var marker; google.maps.event.addListener(map, 'click', function(event) { placeMarker(event.latLng); }); function placeMarker(location) { if (marker == null) { marker = new google.maps.Marker({ position: location, map: map, zoom:13 }); } else { marker.setPosition(location); } geocoder.geocode( { location: location }, ( results = google.maps.GeocoderResult, status= google.maps.GeocoderStatus ) => { if (status === "OK") { if (results[0]) { console.log (results[0].address_components); var address_components = results[0].address_components; var components={}; jQuery.each(address_components,function(k,v1) {jQuery.each(v1.types,function(k2, v2){components[v2]=v1.long_name});}); var city, postal_code,state,country,sublocality,street_number,route; console.log(components); if(components.locality) { city = components.locality; } if(!city) { city = components.administrative_area_level_1; } if(components.postal_code) { postal_code = components.postal_code; } if(components.postal_code) { postal_code = components.postal_code; } if(components.administrative_area_level_1) { state = components.administrative_area_level_1; } if(components.route) { route = components.route; } if(components.sublocality_level_1) { sublocality = components.sublocality_level_1; } if(components.country) { country = components.country; } if(components.street_number) { street_number = components.street_number; } $('#input-address-formated').val(results[0].formatted_address); $('#input-address').val(state); $('#input-city').val(city); $('#input-country').val(country); $('#input-postal-code').val(postal_code); $('#input-street').val(route+', '+sublocality); $('#input-interior-number').val(street_number); $('#input-exterior-number').val(street_number); $('#latitude').val(marker.getPosition().lat()); $('#longitude').val(marker.getPosition().lng()); } else { window.alert("No results found"); } } else { window.alert("Geocoder failed due to: " + status); } } ); } } google.maps.event.addDomListener(window, 'load', initialize); </script>
Gracias por leer este pequeño ejemplo. Si tienes alguna pregunta o sugerencia, no dudes en dejarla en los comentarios, me gustaría saber tu opinión.