8

I'm trying to get google places autocomplete working with predefined data but so far no luck.

Lets say I have this text "Alaskan Way South, Seattle, WA" in an input field predefined like this:

<input id="ev-loc-input" size="60" value="Alaskan Way South, Seattle, WA" />

I initialize googles autocomplete on it and I would like to somehow trigger it so it looks for this address right when the page loads.

There seem to be only one documented event for it "place_changed":

google.maps.event.addListener(events_autocomplete, 'place_changed', function(){..

I cant use this one cause it gets triggered after the address lookup is already done. I couldn't find a list of events available - maybe anyone knows?

Any help much appreciated!

Alex R
  • 11,364
  • 15
  • 100
  • 180
Krabats
  • 325
  • 4
  • 12

1 Answers1

6

I finally figured this out! I've been working on this for 2 hours!

Anyway, you need to focus on your input element, but you can't do it right away. You need to delay it.

So, like this...

setTimeout(func, 2000);
function func() {
    input.focus();
    selectFirstResult();
}

Here is the my code, and it works.

$(function() {
    var input = document.getElementById('searchTextField');
    input.value = "{{ $user["location"] }}";//I'm using laravel
    //You won't need the above line if you're already filling in the value of
    //the input field - I'm going to get this working without the map as well
    //I'll come back and post that later this weekend   
    var lat = -33.8688,
    lng = 151.2195,
    latlng = new google.maps.LatLng(lat, lng),
    image = 'http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png';     
    var mapOptions = {           
            center: new google.maps.LatLng(lat, lng),           
            zoom: 13,           
            mapTypeId: google.maps.MapTypeId.ROADMAP         
        },
        map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions),
        marker = new google.maps.Marker({
            position: latlng,
            map: map,
            icon: image
         });
    var autocomplete = new google.maps.places.Autocomplete(input, {
        types: ["geocode"]
    });          
    autocomplete.bindTo('bounds', map); 
    var infowindow = new google.maps.InfoWindow(); 
    google.maps.event.addListener(autocomplete, 'place_changed', function() {
        infowindow.close();
        var place = autocomplete.getPlace();
        if (place.geometry.viewport) {
            map.fitBounds(place.geometry.viewport);
        } else {
            map.setCenter(place.geometry.location);
            map.setZoom(17);  
        }
        moveMarker(place.name, place.geometry.location);
    });  
    $("input").focusin(function () {
        $(document).keypress(function (e) {
            if (e.which == 13) {
                 selectFirstResult();   
            }
        });
    });
    $("input").focusout(function () {
        if(!$(".pac-container").is(":focus") && !$(".pac-container").is(":visible"))
            selectFirstResult();
    });
     function selectFirstResult() {
        infowindow.close();
        $(".pac-container").hide();
        var firstResult = $(".pac-container .pac-item:first").text();
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({"address":firstResult }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                var lat = results[0].geometry.location.lat(),
                lng = results[0].geometry.location.lng(),
                placeName = results[0].address_components[0].long_name,
                latlng = new google.maps.LatLng(lat, lng);
                moveMarker(placeName, latlng);
                $("input").val(firstResult);
            }
        });   
     }
     function moveMarker(placeName, latlng){
        marker.setIcon(image);
        marker.setPosition(latlng);
        infowindow.setContent(placeName);
        infowindow.open(map, marker);
     }
    setTimeout(func, 2000);
    function func() {
        input.focus();
        selectFirstResult();
    }
});
adprocas
  • 1,863
  • 1
  • 14
  • 31
  • 4
    Using this code gives me intense feelings of remorse. There must be a better way. – Pierre Jul 07 '14 at 13:15
  • 1
    Feelings of remorse? There's nothing "wrong" with the code. I have actually dug a bit further into this since this posting, and from whta I can tell this is really the only way to do it. I think it has to do with lazy loading that Google uses. They would do that so your site doesn't sit around waiting for Google to respond. So, it's annoying, but it's actually happening as a result of a good thing, I think. – adprocas Aug 14 '14 at 20:15
  • 1
    It's 2023. I couldn't find another working solution. Google Places SDK developers: if you are reading, please enhance your SDK to support autofill. Thank you in advance. – Billy May 22 '23 at 13:12