1

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

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

1 回答 1

0

你不能强制谷歌的函数返回你的回调值,所以你能做的最好的就是从你的回调中调用另一个函数。

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());
        }
      }
    );
于 2019-10-03T16:07:48.523 回答