0

I am working on a core piece of my form functionality that finds the distance between two ZIP codes. It does find the distance accurately, but unfortunately, this Google Distance Matrix API is also searching for existing area codes, which can result in random and unnecessary mileage returns.

Currently, I can find the mileage between 64154 and 816 (19.1), but I would like to completely omit the return of any AREA CODE data.

This is the function that returns said data:

 handleChange = (e) => {
    const name = e.target.name
    const value = e.target.value
    this.setState({
      [name]: value
  //call back function to make sure we get the last character from the user input
    }, () => {
      this.getMiles(this.state.origin, this.state.destination)
    })
  }

  getMiles = (origin, destination) => {
    const {google} = this.props
     let service = new google.maps.DistanceMatrixService()
        console.log(origin)
        console.log(destination)
         service.getDistanceMatrix({
          origins: [origin],
          destinations: [destination],
          travelMode: 'DRIVING',
          unitSystem: google.maps.UnitSystem.IMPERIAL,
          avoidHighways: false,
          avoidTolls: false
        }, (response, status) => {
          if (status !== 'OK') {
            alert('Error was: ' + status);
          } else {
            let originList = response.originAddresses;
            let destinationList = response.destinationAddresses;
            if (response.rows[0].elements[0].status === 'NOT_FOUND'){
              return false
            } else{
                this.setState({mileage: response.rows[0].elements[0].distance.text.replace("mi", " ")})
            }
        }
    });
  }

I can't find anything in the documentation that would allow me to filter out certain address types. I have even tried to put different form limitations regarding character length, which works for the most part, but the user can still put three digits in and "space" all the way to the end of the input. This will, unfortunately, bypass my conditional and return the data for the AREA CODE because the character length that I am looking for will be fulfilled "816 ".length === 5

AttemptedMastery
  • 738
  • 6
  • 21

1 Answers1

0

Well, I just ended up using a regex pattern to check to see if the string contains 5 digits that are numbers.

What this does is, it doesn't prevent the API from returning AREA CODE searches but it does prevent my mileage from calculating by constantly setting it to zero:

let fiveNumberMatch = /^[0-9]{5}$/;

<h1>{!this.state.origin.match(fiveNumberMatch) || !this.state.destination.match(fiveNumberMatch) ? this.state.mileage = 0 : this.state.mileage}</h1>

Works for now!

AttemptedMastery
  • 738
  • 6
  • 21