Home > Back-end >  Uncaught ReferenceError: google is not defined in api direction service
Uncaught ReferenceError: google is not defined in api direction service

Time:12-01

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 >
    <div >
      <div >
        <div >
            <div >
              <div >
                <input type="text"  id="start" placeholder="Lokasi">
              </div>
            </div>
            <div >
              <div >
                <i ></i>
              </div>
            </div>
            <div >
              <div >
                <input type="text"  id="end" placeholder="Tujuan">
              </div>
            </div>

          <div >
            <div >
            </div>

            <div >
            </div>
            <div >
            </div>
          </div>
    
        </div>
        <div >
          <div  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

CodePudding user response:

  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.

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  style="height:100%;">
      <div  style="height:100%;">
        <div  style="height:100%;">
          <div >
            <div >
              <div >
                <input type="text"  id="start" placeholder="Lokasi">
              </div>
            </div>
            <div >
              <div >
                <i ></i>
              </div>
            </div>
            <div >
              <div >
                <input type="text"  id="end" placeholder="Tujuan">
              </div>
            </div>

            <div >
              <div >
              <button id="pesan-btn">
              start
              </button>
              </div>

              <div >
              </div>
              <div >
              </div>
            </div>

          </div>
          <div  style="height:70%;">
            <div  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>

  • Related