在提交表格之前计算距离

时间:2014-11-13 16:18:04

标签: javascript google-maps-api-3 onchange form-fields

我正在尝试计算从工作场所到目的地的距离变化。 我有一个包含3个字段的表单: 日期 目的地 距离 我想通过输入目的地地址来获得距离 - 这应该在我提交表单之前发生(为了获得最佳用户体验)。 我正在尝试使用google maps api,但无法将目标字段中的输入输入到js code var DestinationA中。我也在使用" onchange"在提交之前获得inout。

然后我的下一步是将距离结果输入表格字段距离。

非常感谢任何帮助。

以下是我的测试网站:www.e-kl.dk/s/_kort.asp

这是我的代码:

<%@LANGUAGE="VBSCRIPT" CODEPAGE="1252"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>test</title>

    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
    <style>
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }

      #map-canvas {
    height: 200px;
    width: 200px;
    position: absolute;
    left: 3px;
    top: 92px;
    z-index: 1;
      }
      #content-pane {
        float:right;
        width:48%;
        padding-left: 2%;
      }
      #outputDiv {
    font-size: 11px;
    height: 50px;
    width: 876px;
    position: absolute;
    left: 0px;
      }
    </style>

</head>

<script>
var map;
var geocoder;
var bounds = new google.maps.LatLngBounds();
var markersArray = [];

var origin1 = 'Gl. Hovedgade 10, Denmark';
// var destinationA = 'ballerup'; //THIS WORKS but I need the user input....

// var destinationA = document.form1.destination;  //did not work

// var addressField = document.getElementById('destination');   //did not work
// var destinationA = addressField.value;       

// var destinationA = $("#destination").val();      //did not work


var destinationIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=D|FF0000|000000';
var originIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=O|FFFF00|000000';

function initialize() {
  var opts = {
    center: new google.maps.LatLng(55.876, 12.5),
    zoom: 15
  };
  map = new google.maps.Map(document.getElementById('map-canvas'), opts);
  geocoder = new google.maps.Geocoder();
}

function calculateDistances() {
  var service = new google.maps.DistanceMatrixService();
  service.getDistanceMatrix(
    {
      origins: [origin1],
      destinations: [destinationA],
      travelMode: google.maps.TravelMode.DRIVING,
      unitSystem: google.maps.UnitSystem.METRIC,
      avoidHighways: false,
      avoidTolls: false
    }, callback);
}

function callback(response, status) {
  if (status != google.maps.DistanceMatrixStatus.OK) {
    alert('Error was: ' + status);
  } else {
    var origins = response.originAddresses;
    var destinations = response.destinationAddresses;
    var outputDiv = document.getElementById('outputDiv');
    outputDiv.innerHTML = '';
    deleteOverlays();

    for (var i = 0; i < origins.length; i++) {
      var results = response.rows[i].elements;
      addMarker(origins[i], false);
      for (var j = 0; j < results.length; j++) {
        addMarker(destinations[j], true);
        outputDiv.innerHTML += 'Tegnestuen' + ' til ' + destinations[j]
            + ': ' + results[j].distance.text;
      }
    }
  }
}

function addMarker(location, isDestination) {
  var icon;
  if (isDestination) {
    icon = destinationIcon;
  } else {
    icon = originIcon;
  }
  geocoder.geocode({'address': location}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      bounds.extend(results[0].geometry.location);
      map.fitBounds(bounds);
      var marker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location,
        icon: icon
      });
      markersArray.push(marker);
    } else {
      alert('Geocode was not successful for the following reason: '
        + status);
    }
  });
}

function deleteOverlays() {
  for (var i = 0; i < markersArray.length; i++) {
    markersArray[i].setMap(null);
  }
  markersArray = [];
}

google.maps.event.addDomListener(window, 'load', initialize);

    </script>


<body>
    <div id="outputDiv">
      <form id="form1" name="form1" method="post" action="">
        date
          <input name="date" type="text" value="" id="date"/>
        destination
        <input name="destination" type="text" value="" id="destination" onchange="calculateDistances();"/>
        distance
        <input name="distance" type="text" value="" id="distance" />
      </form>
    </div>
    <div id="map-canvas"></div>
  </body>
</html>

1 个答案:

答案 0 :(得分:0)

在onload事件触发之前,您无法访问document.getElementById('destination')。最好在calculateDistances函数中获取该值(如果需要):

function calculateDistances() {

    var addressField = document.getElementById('destination'); //did not work
    var destinationA = addressField.value;
    var service = new google.maps.DistanceMatrixService();
    service.getDistanceMatrix({
        origins: [origin1],
        destinations: [destinationA],
        travelMode: google.maps.TravelMode.DRIVING,
        unitSystem: google.maps.UnitSystem.METRIC,
        avoidHighways: false,
        avoidTolls: false
    }, callback);
}

working fiddle