harry robinson
harry robinson

Reputation: 49

Google places & directions API

I have been working on a courier calculator to calculate the cost for a delivery of a parcel from one location to another, this function is working however i want to add in the google places autocomplete API to automatically complete the input fields for start and end locations.

I have tried adding the places key onto the google script request however it crashes the entire application

This is the fiddle with just the google directions API and the app JS:

https://jsfiddle.net/1k8035gt/

 var directionDisplay;
 var directionsService = new google.maps.DirectionsService();
 var map;

 function initialize() {
 directionsDisplay = new google.maps.DirectionsRenderer();
 var northampton = new google.maps.LatLng(52.2405, 0.9027);
 var myOptions = {
 zoom: 12,
 mapTypeId: google.maps.MapTypeId.ROADMAP,
 center: northampton
 }

  map = new google.maps.Map(document.getElementById("map_canvas"), 
  myOptions);
  directionsDisplay.setMap(map);
   }

   function calcRoute() {
  var start              = document.getElementById("start").value;
  var end                = document.getElementById("end").value;
  var distanceInput      = document.getElementById("distance");
  var distanceInputMiles = document.getElementById("distance_miles");
  var roundtripInput     = document.getElementById("round_trip_miles");
  var finalcostInput     = document.getElementById("finalcost");
  var billableInput      = document.getElementById("billable_miles");
  var unitsInput         = document.getElementById("units");
  var travelCostInput    = document.getElementById("travel_cost");
  var parcelweight       = $("#parcel_weight").val();
  var additions          = 0;

  //DEFINE MY VARS
   if ($("#van_type").val() == 'SMALL') {
    additions+=5;
    console.log(additions);
     }
 if ($("#van_type").val() == 'SWB') {
    additions+=10;
    console.log(additions);
    }
  if ($("#van_type").val() == 'LWB') {
    additions+=15;
    console.log(additions);
    }
 if ($("#van_type").val() == 'XLWB') {
    additions+=20;
    console.log(additions);
    }


  console.log(parcelweight);


  var request = {
  origin: start,
  destination: end,
  travelMode: google.maps.DirectionsTravelMode.DRIVING
  };


 directionsService.route(request, function(response, status) {
  if (status == google.maps.DirectionsStatus.OK) {
    directionsDisplay.setDirections(response);
     var distance_km          = response.routes[0].legs[0].distance.value / 
  1000
  var distance_mi          = Math.round( distance_km * 0.6214 );
  var roundtrip            = distance_mi * 2;
  var finalcost            = additions + roundtrip;
  distanceInputMiles.value = distance_mi;
  roundtripInput.value     = roundtrip;
  finalcostInput.value     = finalcost;
   }
   });
   }

  initialize();

Upvotes: 1

Views: 368

Answers (1)

SphynxTech
SphynxTech

Reputation: 1849

First, you should declare an input who will "autocomplete" locations. The declaration is very simple: var autocomplete = new google.maps.places.Autocomplete(yourInput);.

Next you have to add a listener who will be able to interact enter the map or the interface and the autocomplete input. Here the declaration is very easy too:

autocomplete.addListener('place_changed', function () {
        infowindow.close();
        var place = autocomplete.getPlace();
        if (!place.geometry) {
            window.alert("Veuillez sélectionner un choix dans la liste.");
            return;
        }

         // Do what ever you want like:

         map.setCenter(place.geometry.location);

}

Note: You can consult the documentation here for the format of the result.

You can also consult the google documentation about autocomplete.

Finally, your code should looks like this:

var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;

function initialize() {
  directionsDisplay = new google.maps.DirectionsRenderer();
  var northampton = new google.maps.LatLng(52.2405, 0.9027);
  var myOptions = {
    zoom: 12,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: northampton
  }
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  directionsDisplay.setMap(map);
  
  var startInput = /** @type {!HTMLInputElement} */(document.getElementById('start'));
  var startAutocomplete = new google.maps.places.Autocomplete(startInput);
        
  startAutocomplete.addListener('place_changed', function () {
    var place = startAutocomplete.getPlace();
    if (!place.geometry) {
      window.alert("Veuillez sélectionner un choix dans la liste.");
      return;
    }

    map.setCenter(place.geometry.location);
  });
  
  var endInput = /** @type {!HTMLInputElement} */(document.getElementById('end'));
  var endAutocomplete = new google.maps.places.Autocomplete(endInput);
        
  endAutocomplete.addListener('place_changed', function () {
    var place = endAutocomplete.getPlace();
    if (!place.geometry) {
      window.alert("Veuillez sélectionner un choix dans la liste.");
      return;
    }

    map.setCenter(place.geometry.location);
  });
  
        
  
}

function calcRoute() {
  var start              = document.getElementById("start").value;
  var end                = document.getElementById("end").value;
  var distanceInput      = document.getElementById("distance");
  var distanceInputMiles = document.getElementById("distance_miles");
  var roundtripInput     = document.getElementById("round_trip_miles");
  var finalcostInput     = document.getElementById("finalcost");
  var billableInput      = document.getElementById("billable_miles");
  var unitsInput         = document.getElementById("units");
  var travelCostInput    = document.getElementById("travel_cost");
  var parcelweight       = $("#parcel_weight").val();
  var additions          = 0;
  
  //DEFINE MY VARS
  if ($("#van_type").val() == 'SMALL') {
        additions+=5;
        console.log(additions);
        }
  if ($("#van_type").val() == 'SWB') {
        additions+=10;
        console.log(additions);
        }
  if ($("#van_type").val() == 'LWB') {
        additions+=15;
        console.log(additions);
        }
  if ($("#van_type").val() == 'XLWB') {
        additions+=20;
        console.log(additions);
        }
  
  
  console.log(parcelweight);
  
  
  var request = {
    origin: start,
    destination: end,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
  };
  

  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
      var distance_km          = response.routes[0].legs[0].distance.value / 1000
      var distance_mi          = Math.round( distance_km * 0.6214 );
      var roundtrip            = distance_mi * 2;
      var finalcost            = additions + roundtrip;
      distanceInputMiles.value = distance_mi;
      roundtripInput.value     = roundtrip;
      finalcostInput.value     = finalcost;
    }
  });
}

initialize();
    #map_canvas {
  height: 300px;
}
input {
  margin-bottom: 1em;
}
<div>
  <p>
    <label for="start">Start: </label>
    <input type="text" name="start"  id="start" />
    <br/>
    <label for="end">End: </label>
    <input type="text" name="end" id="end" />
    <br/>
    <label for="van_type">Parcel Weight: </label>
    <select id="van_type">
        <option value="SMALL">Small Van ( Upto 400KG )</option>
        <option value="SWB"Transit SWB Van ( Upto 850KG )</option>
        <option value="LWB">LWB Van ( Upto 1300KG )</option>
        <option value="XLWB">XLWB Van ( Upto 1150KG )</option>
    </select>
    <br/><br/>
    <input type="submit" value="Calculate Route" onclick="calcRoute()" />
  </p>
  <p>
    
    <label for="distance">Distance (mi): </label>
    <input type="text" id="distance_miles" readonly="true" />
    
    <label for="distance">Round Trip (mi): </label>
    <input type="text" id="round_trip_miles" readonly="true" />
    
    <label for="finalcost">Final cost £: </label>
    <input type="text" id="finalcost" readonly="true" />
  </p>
</div>
<div id="map_canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAAdFqcFgkBXdekUDy_R_czpgHLRPoVwmQ&libraries=places"></script>
<script src='//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>

Note: I change the callback of the autocomplete library. I do not need a function to initialize your autocomplete. I put the initialization of it into the function initialize.

Upvotes: 2

Related Questions