javascriptlaravelgoogle-maps-api-3autocompletesearch-box

Searchbox google maps api cannot show the autocomplete


I'm creating a map for a location search but my searchbox doesn't show autocomplete. I followed the tutorial on https://www.youtube.com/watch?v=D_jUFC-Xktk&t=3s

this is my map not showing autocompelete this my maps

index.blade.php

<script async src="https://maps.googleapis.com/maps/api/js?key=keysensor&libraries=places"></script>
<div class="row">
   <div class="col-lg-12">
     <style>
     #map {
        width: 100%;
        height: 500px;
     }
    </style>
    <label for=""><b>ADRESSTANAH <font style="color: red;">*</font></b></label>
    <div class="form-group">
       <input type="text" id="searchmap">
       <div id="map"></div>
    </div>
</div>
var map = new google.maps.Map(document.getElementById('map'),{
    center:{
        lat:-6.8909965,
        lng:110.6046387
    },
    zoom:15
});

var marker = new google.maps.Marker({
    position: {
        lat:-6.8909965,
        lng:110.6046387
    },
    map : map,
    draggable : true
});

var searchBox = new google.maps.places.SearchBox(document.getElementById('searchmap'));

google.maps.event.addListener(searchBox, 'places_changed', function(){

    var places = searchBox.getPlaces();
    var bounds = new google.maps.LatLngBounds();
    var i, place;

    for(i=0; place=places[i];i++){
        bounds.extends(place.geometry.location);
        marker.setPosition(place.geometry.location);
    }

    map.fitBounds(bounds);
    map.setZoom(15);
});

google.maps.event.addListener(marker, 'position_changed', function(){
    var lat = marker.getPosition().lat();
    var lng = marker.getPosition().lng();

    $('#lat').val(lat);
    $('#lng').val(lng);
});

I want to show autocomplete in the searchbox. please help me to solve it. thank u.


Solution

  • You need to have a callback parameter in your request that would call the needs to be executed. For example:

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

    Then, you will put all javascript code inside the initMap function. Here is a working JSBin sample: https://jsbin.com/qerofoqudo/edit?html,js,console,output