2

I have a question concerning the Google API Direction with JavaScript, I'm using it for the first time.

I'm developing a carpooling website. I want to create a direction between two places that I got from an input using Google Autocomplete. I've managed to get my two LatLng coordinates that I passed as a string to put in the origin and destination fields. However, it echoes "Directions request failed due to NOT_FOUND".

Could anyone help me? Thank you :)

HTML Fields

<input type="text" name="departure" id="autocomplete_address" />
<input type="button" id="departure_check" value="Add this departure" />

<input type="text" name="arrival" id="autocomplete_address2" />
<input type="button" id="arrival_check" value="Add this destination" />

JavaScript:

let latorigine
let latdestination

function initMap () {
  const geocoder = new google.maps.Geocoder()
  const directionsService = new google.maps.DirectionsService()
  const directionsDisplay = new google.maps.DirectionsRenderer()

  const map = new google.maps.Map(document.getElementById('searchmap'), {
    center: { lat: 50.437616, lng: 2.809546 },
    zoom: 15,
  })

  directionsDisplay.setMap(map)

  // AUTOCOMPLETE
  const departure_input = (document.getElementById('autocomplete_address'))
  const arrival_input = (document.getElementById('autocomplete_address2'))
  const options = {
    types: [ 'address' ],
    componentRestrictions: { country: 'fr' },
  }
  const departure_autocomplete = new google.maps.places.Autocomplete(departure_input, options)
  const arrival_autocomplete = new google.maps.places.Autocomplete(arrival_input, options)

  document.getElementById('departure_check').addEventListener('click', function (latorigine) {
    const departure_place = departure_autocomplete.getPlace()
    latorigine = ` " ${departure_place.geometry.location.lat()}, ${departure_place.geometry.location.lng()} " `
    console.log(latorigine)
  })

  document.getElementById('arrival_check').addEventListener('click', function (latdestination) {
    const arrival_place = arrival_autocomplete.getPlace()
    latdestination = ` " ${arrival_place.geometry.location.lat()}, ${arrival_place.geometry.location.lng()} " `
    console.log(latdestination)
  })
}

// END INITMAP
function trajectdirection (directionsService, directionsDisplay, latorigine, latdestination) {
  directionsService.route(
    {
      origin: latorigine.toString(),
      destination: latdestination.toString(),
      travelMode: 'DRIVING',
    },
    function (response, status) {
      if (status === 'OK') {
        directionsDisplay.setDirections(response)
      }
      else {
        window.alert(`Directions request failed due to ${status}`)
      }
    }
  )
}
Vl4dimyr
  • 876
  • 9
  • 27

0 Answers0