calculate distance before submitting form

424 views Asked by At

I am trying to calculate a distance from my workplace to a destination that varies. I have a form with 3 fields: date destination distance I would like get the distance by just typing in the destination address - this should happen before I submit the form (for best user experience). I am trying to use google maps api but can't get the input in the destination field into the js code var DestinationA. I am also using the "onchange" to get the inout before submitting.

My next step is then to get the distance result into the form field distance.

Any help is much appreciated.

Here is my test-site: www.e-kl.dk/s/_kort.asp

Here is my code:

<%@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

There are 1 answers

5
geocodezip On BEST ANSWER

You can't access document.getElementById('destination') until the onload event has fired. Best to get that value in the calculateDistances function (when it is needed):

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