Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Maps Autocomplete not working for some reason

Here is the function:

function initializeMap(){
        var LatLng = {lat: 20.23, lng: -8.28460};
        var mapOptions = {
            center: LatLng,
            zoom: 6,
            scrollwheel:false
        }

        var map = new google.maps.Map(document.getElementById('map'), mapOptions);

        var marker = new google.maps.Marker({
                position: LatLng,
                map: map,
                draggable: true,
                title: "Binko"
        });

        var input = document.getElementById('accommodation_address');
        var autocomplete = new google.maps.places.Autocomplete(input);
        autocomplete.bindTo('bounds',map);

        google.maps.event.addListener(autocomplete, 'place_changed',function(){
            var place=autocomplete.getPlace();
            if (!place.geometry){
                return;
            }
            if (place.geometry.viewport) {
                map.fitBounds(place.geometry.viewport);
            } else {
                map.setCenter(place.geometry.location);
                map.setZoom(17);
            }

            marker.setPlace( ({
                placeId: place.place_id,
                location: place.geometry.location
            }));
        });
    };

google.maps.event.addDomListener(window, 'load', initializeMap);

I get the uncaught type error, saying autocomplete is not defined, even though I included the library. My API call looks like this: src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&libraries=places">

like image 724
BroDev Avatar asked Mar 04 '16 16:03

BroDev


2 Answers

I have had similar problem. Google maps and autocomplete has worked on my old websites and on localhost but not on new website. I had to create api key and include it in code:

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>

Then I had in developer console (where I have got api key) to enable additional api. Steps:

  1. select your project
  2. in left API Manager menu click on Overview
  3. find Google Places API Web Service(you can type it to search box or find it between Google Maps API)
  4. click on Google Places API Web Service
  5. click on Enable button
like image 185
StevoF Avatar answered Nov 14 '22 09:11

StevoF


Try to do like this:

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initializeMap" async defer></script>

instead of

google.maps.event.addDomListener(window, 'load', initializeMap);

maybe Places library is not loaded

like image 38
Dmitriy Avatar answered Nov 14 '22 09:11

Dmitriy