我不明白为什么“附近的地方”按钮不起作用

时间:2019-07-05 14:51:16

标签: javascript reactjs redux

在我的代码中,有一个按钮负责在距您最近的位置的地图上显示标记,当我单击它时,我可以安全地获取位置数据,但是标记不会出现,并且视觉部分的其余部分(单击地图时创建标记)也停止工作

homepage.jsx

import React, { Component } from 'react';
import './homepage.less';
import { connect } from 'react-redux';
import { saveMarkers, setMarker } from '../../actions/index';
import { Link } from 'react-router-dom';
import { GoogleMap, withScriptjs, withGoogleMap } from 'react-google-maps';
import MapComponent from '../mapComponent/mapComponent';
import store from '../../store';
class HomePage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      zoom: 5,
      selectedValue: 'school',
      currentLatLng: {
        lat: 0,
        lng: 0,
      },
      marks: [],
      loaded: this.props.loaded,
    };
    this.getLoadedMark = this.getLoadedMark.bind(this);
    this.selectedChange = this.selectedChange.bind(this);
    this.placeMarkerLoad = this.placeMarkerLoad.bind(this);
    this.callback = this.callback.bind(this);
    this.setMark = this.setMark.bind(this);
  }
  componentDidMount() {
    this.getGeoLocation();
    console.log(this.state.marks);
  }
  selectedChange(e) {
    this.setState({
      selectedValue: e.target.value,
    });
    console.log(this.state.selectedValue);
  }
  setMark = e => {
    this.setState({
      marks: [
        ...this.state.marks,
        { lat: e.latLng.lat(), lng: e.latLng.lng(), show: true },
      ],
    });
  };

  getLoadedMark() {
    this.setState({
      marks: [...this.state.marks, ...this.state.loaded],
    });
  }
  getGeoLocation = () => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(position => {
        this.setState(prevState => ({
          currentLatLng: {
            ...prevState.currentLatLng,
            lat: position.coords.latitude,
            lng: position.coords.longitude,
          },
        }));
      });
    } else {
      console.log('error');
    }
  };
  placeMarkerLoad() {
    /*global google*/
    let center = new google.maps.LatLng(
      this.state.currentLatLng.lat,
      this.state.currentLatLng.lng
    );
    let map = new google.maps.Map(document.getElementById('map'), {
      center: center,
      zoom: 15,
    });
    let options = {
      location: center,
      radius: 1500,
      type: this.state.selectedValue,
    };
    let service = new google.maps.places.PlacesService(map);
    service.nearbySearch(options, this.callback);
    console.log('GOT IT', options);
  }
  callback(results = google.maps.places.PlaceResult) {
    for (let i = 1; i < results.length; i++) {
      this.setState({
        marks: [
          ...this.state.marks,
          {
            lat: results[i].geometry.location.lat(),
            lng: results[i].geometry.location.lng(),
            show: true,
          },
        ],
      });
    }

    console.log('RESULTS', results);
  }
  render() {
    const { marks } = this.state;
    return (
      <div>
        <div className="HomePage">
          <Link to={`/`}>
            <div className="Home">home</div>
          </Link>
          <Link to={`/about`}>
            <div className="aboutAuthor">about</div>
          </Link>
          <Link to={`/authorization`}>
            <div className="authorization">authorization</div>
          </Link>
        </div>
        <button onClick={() => this.props.saveMarkers(this.state.marks)}>
          save
        </button>
        <button onClick={this.getLoadedMark}>load</button>
        <button
          onClick={() => {
            console.log(this.state.marks);
          }}
        >
          state
        </button>

        <button className="map__button" onClick={this.placeMarkerLoad}>
          nearby place
        </button>
        <select
          className="map__button"
          name="Object types"
          id="1"
          value={this.state.selectedValue}
          onChange={this.selectedChange}
        >
          <option value="school">School</option>
          <option value="restaurant">Restaurant</option>
          <option value="pharmacy">Pharmacy</option>
          <option value="gas_station">Gas station</option>
          <option value="bank">Bank</option>
          <option value="gym">Gym</option>
          <option value="hospital">Hospital</option>
          <option value="travel_agency">Travel agency</option>
          <option value="supermarket">Supermarket</option>
        </select>

        <div
          className="map"
          id="map"
          style={{ width: '100vw', height: '100vh' }}
        >
          <MapComponent
            currentLocation={this.state.currentLatLng}
            onMapClick={this.setMark}
            currentZoom={this.state.zoom}
            marks={marks}
          />
        </div>
      </div>
    );
  }
}
const mapStateToProps = state => {
  return {
    loaded: state.markers,
  };
};
const mapDispatchToProps = {
  saveMarkers,
};
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(HomePage);

和mapComponent.jsx

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { compose, withProps } from 'recompose';
import {
  withScriptjs,
  withGoogleMap,
  GoogleMap,
  Marker,
  Circle,
} from 'react-google-maps';

const MapComponent = compose(
  withProps({
    googleMapURL:
      'https://maps.googleapis.com/maps/api/js?key=AIzaSyCZ7z51hSWmXbLca5zETwnu_dYuW8CbtgM&v=3.exp&libraries=geometry,drawing,places',
    loadingElement: <div style={{ height: `100%` }} />,
    containerElement: <div style={{ height: `400px` }} />,
    mapElement: <div style={{ height: `100%` }} />,
  }),
  withScriptjs,
  withGoogleMap
)(props => (
  <GoogleMap
    defaultZoom={props.currentZoom}
    defaultCenter={{
      lat: props.currentLocation.lat,
      lng: props.currentLocation.lng,
    }}
    onClick={e => props.onMapClick(e)}
  >
    {props.marks.map((mark, index) => (
      <Circle
        key={index}
        center={mark}
        radius={41000}
        options={{
          strokeColor: '#66009a',
          strokeOpacity: 0.8,
          strokeWeight: 2,
          fillColor: `#66009a`,
          fillOpacity: 0.35,
          zIndex: 1,
        }}
      />
    ))}
  </GoogleMap>
));

export default MapComponent;

codesandbox:https://codesandbox.io/s/github/lesha107/map

0 个答案:

没有答案