Iain Simpson
Iain Simpson

Reputation: 8141

Javascript, set variable from contents of text box

I am trying to adapt this Google Maps distance calculator to my needs, but am not overly familiar with plain Javascript, and only Jquery.

I am trying to modify one of the destination variables so that it pulls it from a text box instead. Usually the line reads :

var destinationA = 'pe219px';

But I am trying to change it to the following, usually I would do this with a keyup function to update the value as the person types in jquery, but im not sure what im doing in plain javascript. This is what I have come up with so far, but it doesn't appear to do a lot :

function setValue() { 
destinationA=parseInt(document.getElementById('deliverypostcode').value);
} 

This is the example I am trying to modify https://developers.google.com/maps/documentation/javascript/examples/distance-matrix

This is the whole code :

    <!DOCTYPE html>
    <html>
      <head>
        <title>Distance Matrix service</title>
        <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
        <style>
          html, body {
            height: 100%;
            margin: 0;
            padding: 0;
          }

          #map-canvas {
            height: 100%;
            width: 50%;
          }
          #content-pane {
            float:right;
            width:48%;
            padding-left: 2%;
          }
          #outputDiv {
            font-size: 11px;
          }
        </style>

        <script>


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

    var origin1 = new google.maps.LatLng(53.003604, -0.532764);
    var origin2 = 'pe219px';

        function setValue() { 
        destinationA=parseInt(document.getElementById('deliverypostcode').value);
    } 
    var destinationB = new google.maps.LatLng(53.003604, -0.532764);

    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(53.003604, -0.532764),
        zoom: 8
      };
      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, origin2],
          destinations: [destinationA, destinationB],
          travelMode: google.maps.TravelMode.DRIVING,
          unitSystem: google.maps.UnitSystem.IMPERIAL,
          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 += origins[i] + ' to ' + destinations[j]
                + ': ' + results[j].distance.text + '<br>';
          }
        }
      }
    }

    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>


      </head>
      <body>
        <div id="content-pane">
          <div id="inputs">

       <form name="form1" method="post" action="">
         <label for="deliverypostcode">Your Postcode</label>
         <input type="text" name="deliverypostcode" id="deliverypostcode">
       </form>

            <p><button type="button" onclick="calculateDistances();">Calculate
            distances</button></p>
          </div>
          <div id="outputDiv"></div>
        </div>
        <div id="map-canvas"></div>
      </body>
    </html>

Upvotes: 0

Views: 996

Answers (1)

Delforge
Delforge

Reputation: 792

Your function setValue is never called.

What if you delete it and just place the following line at the begining of calculateDistances ?

var destinationA= document.getElementById('deliverypostcode').value;

This works for me. Also, you don't need to parseInt your text input. Geocoding converts strings to a lat/long coordinates.

Upvotes: 1

Related Questions