Passing result from Google distancematrix to each element in table
Hello, I currently have a task that requires me to retrieve the distance between two selected drop-down locations and run them through Google's distancematrix API which returns a "distance". I am then supposed to pass that distance value to a field in the table, but the caveat is that the table is dynamic and needs to allow for added rows if necessary.
My current setup, I can pass the result to the t_mileage field, but the on change event passes the final value to all totals and not each.
Here is my code:
- $(document).ready(function (){
- $('.ro input').attr('readonly','True');
- $('.ro select').attr('readonly','True');
- $('.personcheck').on('blur', 'select', errorcheck);
- $('.personcheck').on('click', errorcheck);
- $('.personcheck').on('change', errorcheck);
- $('.starting_city select').on('change', mileage_calc);
- $('.ending_city select').on('change', mileage_calc);
- //$('Field475-1').on('click', mileage_calc);
-
- function mileage_calc(){
- $('.miletable tbody tr').each(function(distance){
- var scity = $(this).find('.starting_city :selected').val();
- var sstate = $(this).find('.starting_state :selected').val();
- var ecity = $(this).find('.ending_city :selected').val();
- var estate = $(this).find('.ending_state :selected').val();
- source = (scity + ', ' + sstate);
- destination = (ecity + ', ' + estate);
- var request = {origin: source, destination: destination, travelMode: google.maps.TravelMode.DRIVING};
- var service = new google.maps.DistanceMatrixService();
- service.getDistanceMatrix({origins: [source],destinations: [destination],travelMode: google.maps.TravelMode.DRIVING,unitSystem: google.maps.UnitSystem.IMPERIAL,avoidHighways: false,avoidTolls: false},
- function(response, status) {
- if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
- var distance = response.rows[0].elements[0].distance.value / 1000;
-
- alert(math.ceil(distance));
- //$('.t_mileage input').val(Math.ceil(distance)); //adds initial response to both lines
- //$(this).('.t_mileage input').val(Math.ceil(distance)); //breaks loop/function
- //$(this).find('.t_mileage input').val(distance); //doesn't work
- $(event.target).closest('tr').find('.t_mileage :input').val(Math.ceil(distance)); //doesn't work
- }
- })
- })
- }
And this is what the page looks like:
I have been working on this for quite some time now with no results. Please help as I am at my wits end...