
Categorías:
Objective
Get latitude and longitude from a Google Address when an user type in an input form
HTML
<form method="post"> <input id="place" name="place" type="text" placeholder="Address"> <input id="lat" name="lat" type="hidden" value=""> <input id="lng" name="lng" type="hidden" value=""> <input id="submit-search" type="submit" value="Send"> </form> <!-- call Google Maps javascript files, note libraries=places and language --> <script type="text/javascript" src="//maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places&language=es_ES"></script>
Javascript
<script> var input = (document.getElementById('place')); var searchBox = new google.maps.places.SearchBox((input)); var places; google.maps.event.addListener(searchBox, 'places_changed', function() { places = searchBox.getPlaces(); // if Google returns something, assign latitude and longitude if (places[0]) { $('#lat').val(places[0].geometry.location.lat()); $('#lng').val(places[0].geometry.location.lng()); } }); // avoid submit by return key $("#place").on("keypress", function(e) { if (e.keyCode === 13) return false; }); </script>