Google Autocomplete api and map API throwing error in console and not loading API

Viewed 59

Im trying to get my Google map API to work, i have an auto complete callback and a map callback but when i try to launch through chrome it throws this error Failed to load resource: net::ERR_FILE_NOT_FOUND. Its showing the API callback function as the error but i cant figure out why im pretty sure the callback is correct.

<script async defer src='//maps.googleapis.com/maps/api/js?key=<mykey>=initMap&libraries=places'></script>

1 Answers

You do not need to include the maps api script twice - a single call that features both the libraries you wish to load and the other parameters will suffice.

In a similar vein - rather than a callback in the script uri and a separate init function call the initMap from the uri as per normal and invoke the autocomplete in the same context as the main map invocation. By doing this the scope is the same so both elements can live and work in harmony.

Much of the original code seemed familiar so I adapted what I wrote there slightly

<!doctype html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>Google Maps: </title>
        <style>
            body{
                width:100%;
                height:100vh;
                margin:0;
                padding:0;
                display:flex;
                flex-direction:column;
            }
            #map{
                margin:auto;
                flex:20;
                width:100%;
                min-height:600px;
            }
            form{
                margin:auto;
                display:block;
                flex:1;
                padding:0.25rem 0;
                display:flex;
                flex-direction:row;
                align-items:center;
            }
            form label{ flex:1;background:grey;color:white;padding:0 0 0 1rem}
            form label input{padding:0.5rem}
        </style>
        <script>
            function initMap(){
                let map = new google.maps.Map(document.getElementById("map"), {
                    center: {
                        lat: -34.397,
                        lng: 150.644
                    },
                    zoom: 6,
                });
                let infoWindow = new google.maps.InfoWindow();
                let autocomplete=new google.maps.places.Autocomplete( document.forms.search.location );


                // make a button
                let bttn = document.createElement("button");
                    bttn.textContent = "Pan to Current Location";
                    bttn.classList.add("custom-map-control-button");


                // event handler for geolocation callback
                const clickhandler=()=>{
                    const errorhandler=()=>{
                        infoWindow.setPosition( map.getCenter() );
                        infoWindow.setContent( navigator.geolocation ? 'Error: The Geolocation service failed.' : 'Error: Your browser doesn\'t support geolocation.' );
                        infoWindow.open( map );
                        return false;
                    };
                    const successhandler=( position )=>{
                        const pos = {
                            lat: position.coords.latitude,
                            lng: position.coords.longitude,
                        };
                        infoWindow.setPosition( pos );
                        infoWindow.setContent( "Location found." );
                        infoWindow.open( map );
                        map.setCenter( pos );
                        return true;
                    };
                    const config={
                        enableHighAccuracy:true,
                        timeout:Infinity,
                        maximumAge:60000
                    };

                    if( navigator.geolocation ) {
                        navigator.geolocation.getCurrentPosition( successhandler, errorhandler, config );
                        return true;
                    }
                    return errorhandler();
                };
                
                
                const changehandler=(e)=>{
                    infoWindow.close();
                    
                    let place = autocomplete.getPlace();
                    let marker = new google.maps.Marker({
                        map
                    });
                    
                    map.setCenter( place.geometry.location );
                    map.setZoom( 14 );
                    
                    marker.setPosition( place.geometry.location );
                    marker.setVisible( true );
                    
                    infoWindow.open( map, marker );
                    infoWindow.setContent([ place.name, place.formatted_address ].join('<br />'));
                }
                
                
                // assign event handlers and add the button
                bttn.addEventListener( 'click', clickhandler );
                autocomplete.addListener( 'place_changed', changehandler );
                map.controls[ google.maps.ControlPosition.TOP_CENTER ].push( bttn );
            }
        </script>
        <script async defer src='//maps.googleapis.com/maps/api/js?key=<APIKEY>&callback=initMap&libraries=places'></script>
    </head>
    <body>
        <form name='search'>
            <label>Location: <input name='location' type='text' size='50' /></label>
        </form>
        <div id='map'></div>
    </body>
</html>
Related