Search code examples
javascriptapigoogle-mapsgoogle-maps-api-3maps

Uncaught ReferenceError: google is not defined in api direction service


I am receiving this error when I try to load an HTML page with my map:

Uncaught ReferenceError: google is not defined

I thought it was the order in which I was loading the Google maps API, but I have it at the beginning.

My HTML looks like this:

<body>

  <section class="container">
    <div class="row">
      <div class="col-md-8">
        <div class="row input-user text-center">
            <div class="col-md-5">
              <div class="input-lokasi">
                <input type="text" class="form-control" id="start" placeholder="Lokasi">
              </div>
            </div>
            <div class="col-md-2">
              <div class="icon-lokasi-tujuan">
                <i class="bi bi-caret-right-fill fs-2"></i>
              </div>
            </div>
            <div class="col-md-5">
              <div class="input-tujuan">
                <input type="text" class="form-control" id="end" placeholder="Tujuan">
              </div>
            </div>

          <div class="row text-center">
            <div class="col-md-5">
            </div>

            <div class="col-md-2">
            </div>
            <div class="col-md-5">
            </div>
          </div>
    
        </div>
        <div class="maps-box mt-4">
          <div class="map" id="map">
          </div>
        </div>
      </div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
    integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous">
  </script>
  <!-- <script src="http://maps.googleapis.com/maps/api/js"></script> -->
  <script src="maps.js"></script>
    <script src="https://maps.googleapis.com/maps/api/js?key={}&libraries=places">
    </script>
</body>

my javascript code like this:

var map;
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var harga = 1.7;

map = new google.maps.Map(document.getElementById('map'), {
  center: {
    lat: -7.960996,
    lng: 112.618634
  },
  zoom: 16
});
directionsDisplay.setMap(map);

var start = document.getElementById('start');
var searchStart = new google.maps.places.SearchBox(start);
var end = document.getElementById('end');
var searchEnd = new google.maps.places.SearchBox(end);

var detail = document.getElementById('detail');

var pesanStart = document.getElementById('pesan-btn');

function findRoute() {
  var startAddress = start.value;
  var endAddress = end.value;
  var request = {
    origin: startAddress,
    destination: endAddress,
    travelMode: 'DRIVING'
  };
  directionsService.route(request, function (result, status) {
    if (status == 'OK') {
      directionsDisplay.setDirections(result);
      console.log(result);
      console.log(result.routes[0].legs[0].distance.text);
      console.log(result.routes[0].legs[0].distance.value);

      document.getElementById('distance').innerHTML = result.routes[0].legs[0].distance.text;
      document.getElementById('duration').innerHTML = result.routes[0].legs[0].duration.text;
      document.getElementById('price').innerHTML = 'Rp' + result.routes[0].legs[0].distance.value*harga;


      detail.style.display = 'block';
    } else {
      detail.style.display = 'none';
      alert('Petunjuk arah gagal dimuat, masukkan alamat yang benar!');
    }
  });
}

pesan.addEventListener("click", function (event) {
  if (start.value.trim() != "" && end.value.trim() != "") {
    event.preventDefault();
    findRoute();
  }
});


I hope someone can help me, thank you


Solution

    1. You are including the Google Maps API after the code that depends on it
    <script src="maps.js"></script> <! -- script that depends on the Google Maps JavaScript API v3 -->
    <!-- load of Google Maps JavaScript API -->
    <script src="https://maps.googleapis.com/maps/api/js?key={}&libraries=places"></script>
    
    1. If I reverse those two lines, I get a different error (as @Yrll pointed out in the comments): Uncaught ReferenceError: pesan is not defined

    2. If I fix that (by changing it to pesanStart) as indicated in the comments, I get a third error: Uncaught TypeError: Cannot read properties of null (reading 'addEventListener'), because there is no element with id=pesan-btn in the posted HTML.

    If I fix that, I get a map with no errors, the autocomplete inputs work and the direction service works.

    proof of concept fiddle

    screenshot of map with directions

    code snippet:

    /* 
     * Always set the map height explicitly to define the size of the div element
     * that contains the map. 
     */
    #map {
      height: 100%;
    }
    /* 
     * Optional: Makes the sample page fill the window. 
     */
    html,
    body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
    <!DOCTYPE html>
    <html>
    
      <head>
        <title>Simple Map</title>
        <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
        <!-- jsFiddle will insert css and js -->
      </head>
    
      <body>
        <section class="container" style="height:100%;">
          <div class="row" style="height:100%;">
            <div class="col-md-8" style="height:100%;">
              <div class="row input-user text-center">
                <div class="col-md-5">
                  <div class="input-lokasi">
                    <input type="text" class="form-control" id="start" placeholder="Lokasi">
                  </div>
                </div>
                <div class="col-md-2">
                  <div class="icon-lokasi-tujuan">
                    <i class="bi bi-caret-right-fill fs-2"></i>
                  </div>
                </div>
                <div class="col-md-5">
                  <div class="input-tujuan">
                    <input type="text" class="form-control" id="end" placeholder="Tujuan">
                  </div>
                </div>
    
                <div class="row text-center">
                  <div class="col-md-5">
                  <button id="pesan-btn">
                  start
                  </button>
                  </div>
    
                  <div class="col-md-2">
                  </div>
                  <div class="col-md-5">
                  </div>
                </div>
    
              </div>
              <div class="maps-box mt-4" style="height:70%;">
                <div class="map" id="map">
                </div>
              </div>
            </div>
          </div>
        </section>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous">
    </script>
        <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places"></script>
        <script>
          var map;
          var directionsService = new google.maps.DirectionsService();
          var directionsDisplay = new google.maps.DirectionsRenderer();
          var harga = 1.7;
    
          map = new google.maps.Map(document.getElementById('map'), {
            center: {
              lat: -7.960996,
              lng: 112.618634
            },
            zoom: 16
          });
          directionsDisplay.setMap(map);
    
          var start = document.getElementById('start');
          var searchStart = new google.maps.places.SearchBox(start);
          var end = document.getElementById('end');
          var searchEnd = new google.maps.places.SearchBox(end);
    
          var detail = document.getElementById('detail');
    
          var pesanStart = document.getElementById('pesan-btn');
    
          function findRoute() {
            var startAddress = start.value;
            var endAddress = end.value;
            var request = {
              origin: startAddress,
              destination: endAddress,
              travelMode: 'DRIVING'
            };
            directionsService.route(request, function(result, status) {
              if (status == 'OK') {
                directionsDisplay.setDirections(result);
                console.log(result);
                console.log(result.routes[0].legs[0].distance.text);
                console.log(result.routes[0].legs[0].distance.value);
    
                document.getElementById('distance').innerHTML = result.routes[0].legs[0].distance.text;
                document.getElementById('duration').innerHTML = result.routes[0].legs[0].duration.text;
                document.getElementById('price').innerHTML = 'Rp' + result.routes[0].legs[0].distance.value * harga;
    
    
                detail.style.display = 'block';
              } else {
                detail.style.display = 'none';
                alert('Petunjuk arah gagal dimuat, masukkan alamat yang benar!');
              }
            });
          }
    
          pesanStart.addEventListener("click", function(event) {
            if (start.value.trim() != "" && end.value.trim() != "") {
              event.preventDefault();
              findRoute();
            }
          });
    
        </script>
      </body>
    
    </html>