回调函数返回的值

时间:2019-10-03 15:32:28

标签: reactjs callback frontend google-distancematrix-api distance-matrix

我在通过回调函数获取返回的值时遇到了麻烦(“ dist” =未定义).....我试图多次获取该值,但仍未定义。但是,我可以从控制台获取它。...请一些机构可以提供帮助!

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());
            }
          }
        );
      };

1 个答案:

答案 0 :(得分:0)

您不能强迫Google的函数返回您的回调值,因此,最好的办法是从回调内部调用另一个函数。

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());
        }
      }
    );