Search code examples
reactjscallbackfrontendgoogle-distancematrix-apidistance-matrix

returned value from a callback function


I am having some trouble while getting the returned value by the callback function ("dist" = undefined).....I've tried to get the value so many times but still undefined. However, I can get it from the console....Please Some Body can help!!

calculateDistance = (place, me) => {
        var origin = new window.google.maps.LatLng(
          parseFloat(place.latitude)
          parseFloat(place.longitude)
        );

        var destination = new window.google.maps.LatLng(
          parseFloat(me.latitude),
          parseFloat(me.longitude)
        );

        var service = new window.google.maps.DistanceMatrixService();
        service.getDistanceMatrix(
          {
            origins: [origin],
            destinations: [destination],
            travelMode: window.google.maps.TravelMode.DRIVING,
            avoidHighways: false,
            avoidTolls: false,
            unitSystem: window.google.maps.UnitSystem.metric
          },
          function(response, status) {
            if (
              status === "OK" &&
              response.rows[0].elements[0].status !== "ZERO_RESULTS"
            ) {
              let dist = parseFloat(response.rows[0].elements[0].distance.text);
              return dist;
            } else {
              alert("Error: " + status.toString());
            }
          }
        );
      };

Solution

  • You can't force Google's function to return your callback value, so the best you can do is call another function from inside your callback.

    const setDist = (dist) => {
       //persist your dist somehow, maybe setState?
       this.setState({distance: dist});
    }
    
    service.getDistanceMatrix(
          {
            origins: [origin],
            destinations: [destination],
            travelMode: window.google.maps.TravelMode.DRIVING,
            avoidHighways: false,
            avoidTolls: false,
            unitSystem: window.google.maps.UnitSystem.metric
          },
          function(response, status) {
            if (
              status === "OK" &&
              response.rows[0].elements[0].status !== "ZERO_RESULTS"
            ) {
              let dist = parseFloat(response.rows[0].elements[0].distance.text);
              setDist(dist);
            } else {
              alert("Error: " + status.toString());
            }
          }
        );