如何使用@react-google-maps/api 在 ReactJS 中使用距离矩阵 API?

How do I use Distance Matrix API in ReactJS using @react-google-maps/api?

我正在使用上面的包,但找不到合适的文档来实现代码。目前,这是我的代码:

import React, { Component } from "react";
import { GoogleMap, DistanceMatrixService } from "@react-google-maps/api";
class ExampleDirections extends Component {
  state = {
    response: null,
    travelMode: "DRIVING",
    origin: "",
    destination: "",
  };

  distanceCallback = (response) => {
    console.log("Hello");
    console.log(response);

    if (response !== null) {
      if (response.status === "OK") {
        this.setState(() => ({
          response,
        }));
      } else {
        console.log("response: ", response);
      }
    }
  };

  checkDriving = ({ target: { checked } }) => {
    checked &&
      this.setState(() => ({
        travelMode: "DRIVING",
      }));
  };

  getOrigin = (ref) => {
    this.origin = ref;
  };

  getDestination = (ref) => {
    this.destination = ref;
  };

  onClick = () => {
    if (this.origin.value !== "" && this.destination.value !== "") {
      this.setState(() => ({
        origin: this.origin.value,
        destination: this.destination.value,
      }));
    }
  };

  onMapClick = (...args) => {
    console.log("onClick args: ", args);
  };

  render = () => (
    <div className="map">
      <div className="map-settings">
        <hr className="mt-0 mb-3" />

        <div className="row">
          <div className="col-md-6 col-lg-4">
            <div className="form-group">
              <label htmlFor="ORIGIN">Origin</label>
              <br />
              <input
                id="ORIGIN"
                className="form-control"
                type="text"
                ref={this.getOrigin}
              />
            </div>
          </div>

          <div className="col-md-6 col-lg-4">
            <div className="form-group">
              <label htmlFor="DESTINATION">Destination</label>
              <br />
              <input
                id="DESTINATION"
                className="form-control"
                type="text"
                ref={this.getDestination}
              />
            </div>
          </div>
        </div>

        <div className="d-flex flex-wrap">
          <div className="form-group custom-control custom-radio mr-4">
            <input
              id="DRIVING"
              className="custom-control-input"
              name="travelMode"
              type="radio"
              checked={this.state.travelMode === "DRIVING"}
              onChange={this.checkDriving}
            />
            <label className="custom-control-label" htmlFor="DRIVING">
              Driving
            </label>
          </div>
        </div>

        <button
          className="btn btn-primary"
          type="button"
          onClick={this.onClick}
        >
          Build Route
        </button>
      </div>

      <div className="map-container">
        <GoogleMap
          id="map"
          mapContainerStyle={mapContainerStyle}
          zoom={14}
          center={center}
          options={options}
        >
          <DistanceMatrixService
            options={{
              destinations: this.state.destination,
              origins: this.state.origin,
              travelMode: this.state.travelMode,
            }}
            callback={this.distanceCallback}
          />
          )}
        </GoogleMap>
      </div>
    </div>
  );
}

export default ExampleDirections;

使用此代码时出现以下错误:

InvalidValueError: 在 属性 来源中: 不是数组

我想稍后一起使用所有其他服务,如方向、地点、自动完成。现在我正在尝试单独处理事情,但我只有这个有问题。

包的更好替代品也可以。谢谢

下面的答案解决了我的问题。但是,现在当我尝试将响应保存在某个状态时, API 会被无休止地调用。下面是我的代码。感谢您的帮助。

<DistanceMatrixService
            options={{
              destinations: [{ lat: 1.296788, lng: 103.778961 }],
              origins: [{ lng: 72.89216, lat: 19.12092 }],
              travelMode: "DRIVING",
            }}
            callback={(res) => {
              console.log("RESPONSE", res);
              this.setState({
                totalTime: res.rows[0].elements[0].duration.text,
                totalDistance: res.rows[0].elements[0].distance.text,
              });
            }}
          />

当我只调用 console.log 或当我声明变量并在其中保存值时,它工作正常。但是,当我尝试使用 setState 时,出现了这个问题。

我一直很难弄清楚改进后的 react-google-maps,因为 well.I 距离矩阵的工作方式如下:

<DistanceMatrixService
 options={{
           destinations: [{lat:1.296788, lng:103.778961}],
           origins: [{lng:103.780267, lat:1.291692}],
           travelMode: "DRIVING",
         }}
 callback = {(response) => {console.log(response)}}
/>

确保您的目的地和起点是数组,并且不要忘记启用所有必要的 API。