Home > Software design >  Javascript location search reset for each search instead of append
Javascript location search reset for each search instead of append

Time:11-01

I have the following input field, linked with Google Places so a user can select their location. When they select it, I have a script that calculates how far the user is from a number of preset destinations. This then returns information such as mileage and travel expenses.

Currently, every new search appends the result, however, I need to make this so that if the location is changed, the information is reset.

<label>Location
  <input type="text" name="dest" id="dest" value=""/>
</label>
<div id="outputDiv"></div>

My JS is as follows:

var origin;
var destination;

function initialize() {
  var input = document.getElementById('dest');
  autocomplete = new google.maps.places.Autocomplete(input);
  google.maps.event.addListener(autocomplete, 'place_changed', calculateDistances);

}
function calculateDistances() {
  destination = document.getElementById('dest').value;
  var service = new google.maps.DistanceMatrixService();
  service.getDistanceMatrix(
    {
      origins: ["Tamworth, UK", "Margate, UK", "Brighton, UK", "Bristol, UK", "Birmingham, UK", "Coventry, UK"],
      destinations: [destination],
      travelMode: google.maps.TravelMode.DRIVING,
      unitSystem: google.maps.UnitSystem.IMPERIAL,
      avoidHighways: false,
      avoidTolls: false
    }, calcDistance);
}

function calcDistance(response, status) {
  if (status != google.maps.DistanceMatrixStatus.OK) {
    alert('Error was: '   status);
  } else {
    var origins = response.originAddresses;
    var destinations = response.destinationAddresses;

    const closestCities = [];
    for (var i = 0; i < origins.length; i  ) {
      var results = response.rows[i].elements;

      for (let j = 0; j < results.length; j  ) {
        // If distance is less than 30 miles (48280 metres)
        //if(results[j].distance.value < 48280) {
      const closestCitiesDist = results[j].distance.value
      const closestCitiesName = origins[i]

      closestCities.push({"cityName" : closestCitiesName, "cityDistance" : closestCitiesDist});
    //}
  }
}
//console.log(closestCities)
for (let i = closestCities.length - 1; i > 0; i--) {
  if (closestCities[i].cityDistance < closestCities[i - 1].cityDistance) {
    temp = closestCities[i - 1];
    closestCities[i - 1] = closestCities[i];
    closestCities[i] = temp;
  }
}
// If the closest city is within 30 miles
if(closestCities[0].cityDistance < 48280) {
// list tranvel expenses for all cities here
let expenses = {
  "Margate, UK": 10,
  "Bristol, UK": 20,
  "Coventry, UK": 30,
  "Tamworth, UK": 40,
  "Birmingham, UK": 50,
  "Brighton, UK": 60
}
if(expenses[closestCities[0].cityName]!==undefined)
  travelExpenses  = expenses[closestCities[0].cityName]
else
// FALLBACK: amount if client is within 30 miles of a destination city, but no price is added to the backend
travelExpenses = 35;

} else {
  // if client is not within 30 miles of a destination city, flat fee
  travelExpenses = 100;
  console.log('no cities nearby');
}
console.log(travelExpenses)
outputDiv.innerHTML  = closestCities[0].cityName   ' is the closest city. '   
closestCities[0].cityDistance
          ' metres away. Total Expenses £'   travelExpenses    '<br>';

  }
}

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

CodePudding user response:

Use the assignment operator instead of the addition assignment operator when setting outputDiv's innerHTML.

Your JS should be:

var origin;
var destination;

function initialize() {
  var input = document.getElementById('dest');
  autocomplete = new google.maps.places.Autocomplete(input);
  google.maps.event.addListener(autocomplete, 'place_changed', calculateDistances);

}
function calculateDistances() {
  destination = document.getElementById('dest').value;
  var service = new google.maps.DistanceMatrixService();
  service.getDistanceMatrix(
    {
      origins: ["Tamworth, UK", "Margate, UK", "Brighton, UK", "Bristol, UK", "Birmingham, UK", "Coventry, UK"],
      destinations: [destination],
      travelMode: google.maps.TravelMode.DRIVING,
      unitSystem: google.maps.UnitSystem.IMPERIAL,
      avoidHighways: false,
      avoidTolls: false
    }, calcDistance);
}

function calcDistance(response, status) {
  if (status != google.maps.DistanceMatrixStatus.OK) {
    alert('Error was: '   status);
  } else {
    var origins = response.originAddresses;
    var destinations = response.destinationAddresses;

    const closestCities = [];
    for (var i = 0; i < origins.length; i  ) {
      var results = response.rows[i].elements;

      for (let j = 0; j < results.length; j  ) {
        // If distance is less than 30 miles (48280 metres)
        //if(results[j].distance.value < 48280) {
      const closestCitiesDist = results[j].distance.value
      const closestCitiesName = origins[i]

      closestCities.push({"cityName" : closestCitiesName, "cityDistance" : closestCitiesDist});
    //}
  }
}
//console.log(closestCities)
for (let i = closestCities.length - 1; i > 0; i--) {
  if (closestCities[i].cityDistance < closestCities[i - 1].cityDistance) {
    temp = closestCities[i - 1];
    closestCities[i - 1] = closestCities[i];
    closestCities[i] = temp;
  }
}
// If the closest city is within 30 miles
if(closestCities[0].cityDistance < 48280) {
// list tranvel expenses for all cities here
let expenses = {
  "Margate, UK": 10,
  "Bristol, UK": 20,
  "Coventry, UK": 30,
  "Tamworth, UK": 40,
  "Birmingham, UK": 50,
  "Brighton, UK": 60
}
if(expenses[closestCities[0].cityName]!==undefined)
  travelExpenses  = expenses[closestCities[0].cityName]
else
// FALLBACK: amount if client is within 30 miles of a destination city, but no price is added to the backend
travelExpenses = 35;

} else {
  // if client is not within 30 miles of a destination city, flat fee
  travelExpenses = 100;
  console.log('no cities nearby');
}
console.log(travelExpenses)
outputDiv.innerHTML = closestCities[0].cityName   ' is the closest city. '   
closestCities[0].cityDistance
          ' metres away. Total Expenses £'   travelExpenses    '<br>'; //changed line

  }
}

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