Jack
Jack

Reputation: 89

Autocomplete google maps

I am using google maps autocomplete. I want to get the LatLng result. The autocomplete is not working. The code is:

<script src="https://maps.googleapis.com/maps/api/js?key=[API]&libraries=places"></script>
<script>
var geocoder;
function initialize() {
  geocoder = new google.maps.Geocoder();
}
function codeAddress() {
  var input = document.getElementById("address");
  var autocomplete = new google.maps.places.Autocomplete(input);
  var address = document.getElementById("address").value;
  geocoder.geocode( { 'address': address }, function(r, s) {
    alert   (r[0].geometry.location);
  });
}
</script>
<body onload="initialize()">
  <input type="search" id="address">
  <input type="button" value="Submit" onclick="codeAddress()">

</body>

What is the problem?

Upvotes: 0

Views: 861

Answers (1)

MKiss
MKiss

Reputation: 766

Try this way (without your codeAddress() function ):

function initialize() {
    geocoder = new google.maps.Geocoder();
    var input = document.getElementById("address");
    var autocomplete = new google.maps.places.Autocomplete(input);
    autocomplete.addListener('place_changed', function() {
        var place = autocomplete.getPlace();
        if (place.geometry) {
            alert(place.geometry.location);
        }
    });
};

Hope this helps!

Upvotes: 2

Related Questions