Home > OS >  set google origin search box address with a variable
set google origin search box address with a variable

Time:10-05

I'm trying to make origin SearchBox destination be string with legit direction, but when I do so I still need to select the first option for it to work (to calculate distance).

Got the this searching around to calculate distance between 2 points and it works perfectly: enter image description here

But what happens is that I still have to click on the origin search box then this list all possible locations which in my case is the first one, how can I make the map either auto select the first option or recognize the address that is set in the input value?

    <script>

   function initMap() {
   var map = new google.maps.Map(document.getElementById('map-canvas'), {
  center: {
  lat: 9.0271554,
   lng: 79.4816371
         },
         zoom: 15
        });

     var marker = new google.maps.Marker({
     map: map,
     draggable: false
   });


      if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
  initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
  map.setCenter(initialLocation);
         /*marker.setPosition(initialLocation);         */
         });
        }

      new AutocompleteDirectionsHandler(map);
      }

       /**
       * @constructor
       */
       function AutocompleteDirectionsHandler(map) {
       this.map = map;
       this.originPlaceId = null;
         this.destinationPlaceId = null;
         this.travelMode = 'DRIVING';
      this.avoidTolls = true;
        this.avoidHighways= true;
          //this.provideRouteAlternatives= true,
          this.avoidFerries= true;
        this.directionsService = new google.maps.DirectionsService();
       this.directionsRenderer = new google.maps.DirectionsRenderer();
           this.directionsRenderer.setMap(map);

              var originInput = document.getElementById('orign');
           var destinationInput = document.getElementById('destn');

            var originAutocomplete = new google.maps.places.SearchBox(originInput);

          var destinationAutocomplete =
           new google.maps.places.SearchBox(destinationInput);

        this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
        this.setupPlaceChangedListener(destinationAutocomplete, 'DEST');

          }

          AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(
          autocomplete, mode) {
       var me = this;
       autocomplete.bindTo('bounds', this.map);

       autocomplete.addListener('places_changed', function() {
     var places = autocomplete.getPlaces();
         var place = places[0];

    if (!place.place_id) {
    window.alert('Please select an option from the dropdown list.');
  return;
     }
       if (mode === 'ORIG') {
         me.originPlaceId = place.place_id;
      } else {
        me.destinationPlaceId = place.place_id;
        }
        me.route();
       });
      };

          AutocompleteDirectionsHandler.prototype.route = function() {
    if (!this.originPlaceId || !this.destinationPlaceId) {
      return;
  }
     var me = this;

     this.directionsService.route({
  origin: {
    'placeId': this.originPlaceId
  },
  destination: {
    'placeId': this.destinationPlaceId
  },
  travelMode: this.travelMode,
  avoidTolls: this.avoidTolls
   },
   function(response, status) {
  if (status === 'OK') {
    me.directionsRenderer.setDirections(response);
    computeTotalDistance(response);
  } else {
    window.alert('Directions request failed due to '   status);
  }
    });
    };
    // from Google Maps API: Total distance with waypoints
   // https://stackoverflow.com/questions/12802202/google-maps-api-total-distance-with-waypoints
    function computeTotalDistance(result) {
     var totalDist = 0;
    var totalTime = 0;
    var myroute = result.routes[0];
     for (i = 0; i < myroute.legs.length; i  ) {
     totalDist  = myroute.legs[i].distance.value;
      totalTime  = myroute.legs[i].duration.value;
      }
       totalDist = totalDist / 1000.
      time = (totalTime / 60).toFixed(2)

  document.getElementById("totalkm").innerHTML =""   totalDist   "km" ;
  document.getElementById("totaltime").innerHTML =""   time    " minutos";

 if(totalDist <= 5){
   document.getElementById("totalCost").innerHTML =" $3.50";
  }

 else{
 kmPrice = (totalDist - 5) * 0.75;
 document.getElementById("totalCost").innerHTML ="$"  (kmPrice   3.50).toFixed(2)  "";

     }
    }

   function send_handle(){
   let name=document.getElementById("name").value;
 ///let lastname= document.getElementById("lastname").value;
 let inst= document.getElementById("instructions").value;
 let origin= document.querySelector(".selectButtons input#orign").value;
let destination= document.querySelector(".selectButtons input#destn").value;
let cost= document.getElementById("totalCost").innerHTML;
let distance= document.getElementById("totalkm").innerHTML;
    // win.focus();
     }
    </script>


           
    <html>
   <div  >
   <input type="text" id="orign" placeholder="origen">
   <input type="text" id="destn" placeholder="destino">
   <span> Distancia en KM <div id="totalkm">0km</div> </span>
   <span> Distancia en tiempo <div id="totaltime">o.oo</div> </span>
   <span> costo por envio<div id="totalCost">$0</div></div> </span>
   </div>
   </html>

CodePudding user response:

You can call the places service to get the PlaceId (with your string), then pass that placeId into the constructor for your AutocompleteDirectionsHandler or if you already have the PlaceId (you are allowed to store those), just use it, although you probably want to initialize the origin input with the string.

  var origin = "Allbrook, Panama";
  var originInput = document.getElementById('orign');
  originInput.value = origin;
  const request = {
    query: origin,
    fields: ["name", "geometry", "place_id"],
  };
  var originPlaceId;
  var service = new google.maps.places.PlacesService(map);
  service.findPlaceFromQuery(request, (results, status) => {
    if (status === google.maps.places.PlacesServiceStatus.OK && results) {
      originPlaceId = results[0].place_id;
      console.log("placeId=" originPlaceId " coords=" results[0].geometry.location.toUrlValue(6));
      new AutocompleteDirectionsHandler(map, originPlaceId);
      map.setCenter(results[0].geometry.location);
    }
  });

Add the initial origin placeId to the AutocompleteDirectionsHandler constructor:

function AutocompleteDirectionsHandler(map, originPlaceId) {
  this.map = map;
  this.originPlaceId = originPlaceId;
  // ...

on load: screenshot on load

after selecting destination from dropdown: screenshot after fill in destination

code snippet:

let map;
function initMap() {
  map = new google.maps.Map(document.getElementById('map-canvas'), {
    center: {
      lat: 9.0271554,
      lng: 79.4816371
    },
    zoom: 15
  });

  var origin = "Allbrook, Panama";
  var originInput = document.getElementById('orign');
  originInput.value = origin;
  const request = {
    query: origin,
    fields: ["name", "geometry", "place_id"],
  };
  var originPlaceId;
  var service = new google.maps.places.PlacesService(map);
  service.findPlaceFromQuery(request, (results, status) => {
    if (status === google.maps.places.PlacesServiceStatus.OK && results) {
      originPlaceId = results[0].place_id;
      console.log("placeId=" originPlaceId " coords=" results[0].geometry.location.toUrlValue(6));
      new AutocompleteDirectionsHandler(map, originPlaceId);
      map.setCenter(results[0].geometry.location);
    }
  });

  var marker = new google.maps.Marker({
    map: map,
    draggable: false
  });


  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
      map.setCenter(initialLocation);
      /*marker.setPosition(initialLocation);         */
    });
  }
}

/**
 * @constructor
 */
function AutocompleteDirectionsHandler(map, originPlaceId) {
  this.map = map;
  this.originPlaceId = originPlaceId;
  this.destinationPlaceId = null;
  this.travelMode = 'DRIVING';
  this.avoidTolls = true;
  this.avoidHighways = true;
  //this.provideRouteAlternatives= true,
  this.avoidFerries = true;
  this.directionsService = new google.maps.DirectionsService();
  this.directionsRenderer = new google.maps.DirectionsRenderer();
  this.directionsRenderer.setMap(map);

  var originInput = document.getElementById('orign');
  var destinationInput = document.getElementById('destn');

  var originAutocomplete = new google.maps.places.SearchBox(originInput);

  var destinationAutocomplete =
    new google.maps.places.SearchBox(destinationInput);

  this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
  this.setupPlaceChangedListener(destinationAutocomplete, 'DEST');

}

AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(
  autocomplete, mode) {
  var me = this;
  autocomplete.bindTo('bounds', this.map);

  autocomplete.addListener('places_changed', function() {
    var places = autocomplete.getPlaces();
    var place = places[0];

    if (!place.place_id) {
      window.alert('Please select an option from the dropdown list.');
      return;
    }
    if (mode === 'ORIG') {
      me.originPlaceId = place.place_id;
    } else {
      me.destinationPlaceId = place.place_id;
    }
    me.route();
  });
};

AutocompleteDirectionsHandler.prototype.route = function() {
  if (!this.originPlaceId || !this.destinationPlaceId) {
    return;
  }
  var me = this;

  this.directionsService.route({
      origin: {
        'placeId': this.originPlaceId
      },
      destination: {
        'placeId': this.destinationPlaceId
      },
      travelMode: this.travelMode,
      avoidTolls: this.avoidTolls
    },
    function(response, status) {
      if (status === 'OK') {
        me.directionsRenderer.setDirections(response);
        computeTotalDistance(response);
      } else {
        window.alert('Directions request failed due to '   status);
      }
    });
};
// from Google Maps API: Total distance with waypoints
// https://stackoverflow.com/questions/12802202/google-maps-api-total-distance-with-waypoints
function computeTotalDistance(result) {
  var totalDist = 0;
  var totalTime = 0;
  var myroute = result.routes[0];
  for (i = 0; i < myroute.legs.length; i  ) {
    totalDist  = myroute.legs[i].distance.value;
    totalTime  = myroute.legs[i].duration.value;
  }
  totalDist = totalDist / 1000.
  time = (totalTime / 60).toFixed(2)

  document.getElementById("totalkm").innerHTML = ""   totalDist   "km";
  document.getElementById("totaltime").innerHTML = ""   time   " minutos";

  if (totalDist <= 5) {
    document.getElementById("totalCost").innerHTML = " $3.50";
  } else {
    kmPrice = (totalDist - 5) * 0.75;
    document.getElementById("totalCost").innerHTML = "$"   (kmPrice   3.50).toFixed(2)   "";

  }
}

function send_handle() {
  let name = document.getElementById("name").value;
  ///let lastname= document.getElementById("lastname").value;
  let inst = document.getElementById("instructions").value;
  let origin = document.querySelector(".selectButtons input#orign").value;
  let destination = document.querySelector(".selectButtons input#destn").value;
  let cost = document.getElementById("totalCost").innerHTML;
  let distance = document.getElementById("totalkm").innerHTML;
  // win.focus();
}


function createMarker(place) {
  if (!place.geometry || !place.geometry.location) return;

  const marker = new google.maps.Marker({
    map,
    position: place.geometry.location,
  });

  google.maps.event.addListener(marker, "click", () => {
    infowindow.setContent(place.name || "");
    infowindow.open(map);
  });
}

window.initMap = initMap;
#map-canvas {
  height: 80%;
}


/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<html>
<div >
  <input type="text" id="orign" placeholder="origen" />
  <input type="text" id="destn" placeholder="destino" />
  <span> Distancia en KM <div id="totalkm">0km</div> </span>
  <span> Distancia en tiempo <div id="totaltime">o.oo</div> </span>
  <span> costo por envio<div id="totalCost">$0</div> </span>
</div>
<div id="map-canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places&callback=initMap" async defer></script>

</html>

  • Related