谷歌放置&方向API

时间:2017-07-12 11:37:55

标签: jquery google-maps-api-3 google-places-api

我一直在研究一个快递计算器来计算从一个地方到另一个地方交付包裹的成本,这个功能正在运行但是我想在google地方添加自动完成API以自动完成输入字段的启动和结束地点。

我尝试在Google脚本请求中添加places键,但它会崩溃整个应用程序

这只是谷歌方向API和应用程序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();

1 个答案:

答案 0 :(得分:1)

首先,你应该声明一个输入谁将自动完成"位置。 声明非常简单:var autocomplete = new google.maps.places.Autocomplete(yourInput);

接下来,您必须添加一个能够进行交互的侦听器,输入地图或界面以及自动完成输入。这里的宣言也非常简单:

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);

}

注意:您可以参考文档here了解结果的格式。

您还可以参阅有关自动填充功能的google文档。

最后,您的代码应如下所示:



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>
&#13;
&#13;
&#13;

注意:我更改了自动填充库的回调。我不需要函数来初始化自动完成功能。我把它的初始化放到函数initialize中。