Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Maps API - how to get latitude and longitude from Autocomplete without showing the map?

I'm trying to get latitude and longitude from Autocomplete Google Maps API without showing the map. In my script autocompletion works well, but I can't get the latitude and longitude.

    <script type="text/javascript">         function initialize() {             var options = {        types: ['(cities)']       };             var input = document.getElementById('searchTextField');       var autocomplete = new google.maps.places.Autocomplete(input, options);      }         google.maps.event.addDomListener(window, 'load', initialize);               var geocoder = new google.maps.Geocoder();          var address = autocomplete;            geocoder.geocode( { 'address': address}, function(results, status) {              if (status == google.maps.GeocoderStatus.OK) {          var latitude = results[0].geometry.location.lat();          var longitude = results[0].geometry.location.lng();          alert(latitude);        }       });             </script>
like image 846
MCRD Avatar asked Nov 20 '12 17:11

MCRD


People also ask

How do I find the latitude and longitude of Google Places autocomplete API?

Call Google API with address for lat and long In this step, you will create a javascript code for calling the google geocode v3 api with the address to get latitude and longitude from address. var place = autocomplete. getPlace();


1 Answers

You can use the code below.

<script src="http://maps.googleapis.com/maps/api/js?libraries=places" type="text/javascript"></script>  <script type="text/javascript">     function initialize() {         var input = document.getElementById('searchTextField');         var autocomplete = new google.maps.places.Autocomplete(input);         google.maps.event.addListener(autocomplete, 'place_changed', function () {             var place = autocomplete.getPlace();             document.getElementById('city2').value = place.name;             document.getElementById('cityLat').value = place.geometry.location.lat();             document.getElementById('cityLng').value = place.geometry.location.lng();             //alert("This function is working!");             //alert(place.name);            // alert(place.address_components[0].long_name);          });     }     google.maps.event.addDomListener(window, 'load', initialize);  </script> 

and this part is inside your form:

<input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on" runat="server" />   <input type="hidden" id="city2" name="city2" /> <input type="hidden" id="cityLat" name="cityLat" /> <input type="hidden" id="cityLng" name="cityLng" />   

I hope it helps.

like image 149
Aysegul Avatar answered Oct 20 '22 19:10

Aysegul