[google.maps.places.AutoComplete突然停止工作,然后开始刷新页面,然后再次停止工作于下一次刷新

问题描述 投票:-1回答:1

我刚刚开始使用Google地图,我只想在地图上添加两个点并在其上绘制方向,也想增加半径,以便我可以使用超级算法。

当我在更改一些代码后第一次刷新页面时,google地方不显示任何建议,然后再次刷新时,在我在字段中键入内容时,它开始显示建议。

这里是表单中自动完成的代码。

import {
  addPointA,
  addPointB,
  addSpecialRoute
} from "../../../redux/routesSpecial/actions";
import {
  TextField,
  Grid,
  Checkbox,
  Button,
  FormControlLabel
} from "@material-ui/core";
import { makeStyles } from "@material-ui/core/styles";
import Map from "views/Maps/Maps";
import { connect } from "react-redux";

const style = makeStyles(theme => ({
  container: {
    flexDirection: "row",
    display: "flex",
    flexWrap: "wrap"
  },
  textField: {
    marginLeft: theme.spacing(1),
    marginRight: theme.spacing(1),
    width: 500
  },
  dense: {
    marginTop: 19
  },
  menu: {
    width: 200
  },
  button: {
    height: 40,
    width: 100,
    marginTop: 50,
    left: 50,
    backgroundColor: "black"
  },
  text: {
    color: "white"
  }
}));

class addSpecialRoutes extends PureComponent {
  static propTypes = {};
  constructor(props) {
    super(props);
    this.state = {
      pointA: "",
      pointB: "",
      address: "",
      send: false
    };
    this.fillInAddressA = this.fillInAddressA.bind(this);
    this.fillInAddressB = this.fillInAddressB.bind(this);
  }

  componentDidMount() {
    this.initAutocompleteA();
    this.initAutocompleteB();
  }

  initAutocompleteA() {
    const input = document.getElementById("pointAPlaces");
    const google = window.google;
    this.autocompleteA = new google.maps.places.Autocomplete(input, {
      types: [{ region: "locality" }]
    });
    this.autocompleteA.addListener("place_changed", this.fillInAddressA);
  }

  geolocate() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        const geolocation = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };
        console.log(geolocation);
      });
    }
  }

  fillInAddressA() {
    const componentForm = {
      street_number: "short_name",
      route: "long_name",
      locality: "long_name",
      administrative_area_level_1: "short_name",
      country: "long_name",
      postal_code: "short_name"
    };
    // Get the place details from the autocomplete object.

    this.placeA = this.autocompleteA.getPlace();
    /*this.setState({placeResult: this.place.address_components})*/
    this.setState({
      address: this.placeA
    });

    this.getAddressA(this.placeA.formatted_address);

    for (let component in this.componentForm) {
      this.refs.component.value = "";
      this.refs.component.disabled = false;
    }

    // Get each component of the address from the place details
    // and fill the corresponding field on the form.
    if (this.placeA.address_components) {
      this.placeA.address_components.forEach((component, index) => {
        const addressType = this.placeA.address_components[index].types[0];
        if (componentForm[addressType]) {
          const val = this.placeA.address_components[index][
            componentForm[addressType]
          ];
          console.log(val);
        }
      });
    }
  }

  getAddressA(val) {
    var OK = window.google.maps.GeocoderStatus.OK;
    var geocoder = new window.google.maps.Geocoder();
    geocoder.geocode({ address: val }, (results, status) => {
      if (status !== OK) {
        console.log(status);
      } else {
        console.log(results);
        var latLng = {
          lat: results[0].geometry.location.lat(),
          lng: results[0].geometry.location.lng()
        };
        console.log(results, latLng);
        this.setState({
          pointA: { formatted_address: val, position: latLng }
        });
      }
    });
  }

  initAutocompleteB() {
    console.log(this.refs);
    const input = document.getElementById("autoCompletePlacesPointB");
    console.log(input);
    const google = window.google;
    this.autocomplete = new google.maps.places.Autocomplete(input, {
      types: ["geocode"]
    });

    this.autocomplete.addListener("place_changed", this.fillInAddressB);
  }

  fillInAddressB() {
    const componentForm = {
      street_number: "short_name",
      route: "long_name",
      locality: "long_name",
      administrative_area_level_1: "short_name",
      country: "long_name",
      postal_code: "short_name"
    };
    // Get the place details from the autocomplete object.

    this.place = this.autocomplete.getPlace();
    /*this.setState({placeResult: this.place.address_components})*/
    this.setState({
      address: this.place
    });

    this.getAddressB(this.place.formatted_address);

    for (let component in this.componentForm) {
      this.refs.component.value = "";
      this.refs.component.disabled = false;
    }

    // Get each component of the address from the place details
    // and fill the corresponding field on the form.
    if (this.place.address_components) {
      this.place.address_components.forEach((component, index) => {
        const addressType = this.place.address_components[index].types[0];
        if (componentForm[addressType]) {
          const val = this.place.address_components[index][
            componentForm[addressType]
          ];
          console.log(val);
        }
      });
    }
  }

  getAddressB(val) {
    var OK = window.google.maps.GeocoderStatus.OK;
    var geocoder = new window.google.maps.Geocoder();
    geocoder.geocode({ address: val }, (results, status) => {
      if (status !== OK) {
        console.log(status);
      } else {
        console.log(results);
        var latLng = {
          lat: results[0].geometry.location.lat(),
          lng: results[0].geometry.location.lng()
        };
        this.setState({
          pointB: { formatted_address: val, position: latLng },
          send: true
        });
        console.log(results, latLng);
      }
    });
  }

  addCirclePointA(e) {
    console.log(e);
    this.setState({
      pointA: { ...this.state.pointA, circle: e }
    });
  }

  addCirclePointB(e) {
    this.setState({
      pointB: { ...this.state.pointB, circle: e }
    });
  }

  render() {
    console.log(this.state.pointA, this.state.pointB);
    const classes = style;
    return (
      <Grid container style={{ height: "500px" }}>
        <Grid item xs={3}>
          <form className={classes.container}>
            {/* <TextField
              style={{ width: "300px" }}
              id="pointAPlaces"
              label="Point A"
              type="search"
              margin="normal"
            /> */}
            <input id="pointAPlaces" />
            <br />
            <TextField
              onChange={e => this.addCirclePointA(e.target.valueAsNumber)}
              label="Radius"
              type="number"
              className={classes.textField}
              InputLabelProps={{
                shrink: true
              }}
              margin="normal"
            />
            <br />
            <TextField
              style={{ width: "300px" }}
              id="autoCompletePlacesPointB"
              label="Point B"
              type="search"
              margin="normal"
            />
            <br />
            <TextField
              onChange={e => this.addCirclePointB(e.target.value)}
              label="Radius"
              type="number"
              className={classes.textField}
              InputLabelProps={{
                shrink: true
              }}
              margin="normal"
            />
            <br />
            <TextField
              className={classes.formControl}
              label="Fare"
              id="formatted-numberformat-input"
              // InputProps={{
              //   inputComponent: NumberFormatCustom
              // }}
            />
            <br />
            <FormControlLabel
              style={{ marginTop: "20px" }}
              control={<Checkbox checked={true} color="primary" />}
              label="Same charges apply for revert"
            />
          </form>
          <div>
            <Button
              style={{
                width: "100px",
                height: "40px",
                backgroundColor: "black",
                margin: "20px"
              }}
            >
              <p style={{ color: "white" }}>Add</p>
            </Button>
          </div>
        </Grid>
        <Grid item xs={9}>
          <Map
            polyline={
              this.state.send
                ? { pointA: this.state.pointA, pointB: this.state.pointB }
                : null
            }
          />
        </Grid>
      </Grid>
    );
  }
}

const mapStateToProps = state => {
  return {
    countryCode: state.App.countryCode,
    pointA: state.SpecialRoutes.pointA,
    pointB: state.SpecialRoutes.pointB
  };
};
export default connect(
  mapStateToProps,
  { addPointA, addPointB, addSpecialRoute }
)(addSpecialRoutes);


reactjs google-maps google-places-api google-places react-google-maps
1个回答
0
投票

基本上,问题出在react-google-maps上,它已经过时了,我跳过了它,开始使用react-google-maps / api

© www.soinside.com 2019 - 2024. All rights reserved.