2

我正在尝试使用新输入的位置重新加载谷歌地图,但它没有重新加载。lat和的正确值lng正在从SearchBar组件传回,并且状态正在正确更新。我是新手react-google-maps,所以我不确定是否有其他方法可以更新地图。我假设一旦我更新了状态,谷歌地图就会重新渲染,但事实并非如此。

  1. index.js

    import React, { Component }from 'react';
    import ReactDOM from 'react-dom';
    import Map from './components/map';
    import SearchBar from './components/search_bar'
    import './index.css';
    
    class App extends Component {
      constructor(props) {
        super(props);
    
        this.state = { center: {lat: 37.7547339, lng: -122.4744468 }}
    
      }
    
      locationSearch(term) {
        this.setState({center: JSON.stringify(term)});
      }
    
      render() {
        return (
          <div>
            <div className="row">
              <div className="sidebar col-md-3">
                <SearchBar
                  onSearchTermChange={this.locationSearch.bind(this)}
                  googleMapURL="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places"
                  loadingElement={<div style={{ height: `100%` }} />}
                  containerElement={<div style={{height: '400px'}} />} />
              </div>
              <div className="col-md-9">
                <Map 
                  center={this.state.center}
                  zoom={14}
                  containerElement={<div style={{height:'400px'}} />}
                  mapElement={<div style={{height:100 + '%'}} />} />
              </div>
            </div>
          </div>
        );
      }
    }
    
    ReactDOM.render(<App />, document.querySelector('.container'));
    
  2. search_bar.js

    import React, { Component } from 'react';
    import { withScriptjs } from 'react-google-maps';
    import StandaloneSearchBox from "react-google-maps/lib/components/places/StandaloneSearchBox";
    import _ from 'lodash';
    /*global google*/
    class SearchBar extends Component {
      constructor(props) {
        super(props);
        this.refs = {};
        this.state = { center: {lat:38.5382322, lng:-121.7639065 }};
      }
    
      onSearchBoxMounted(ref) {
        this.searchBox = ref;
      }
      bounds() {
        console.log("bounds");
      }
      onPlacesChanged() {
        const places = this.searchBox.getPlaces();
        const bounds = new google.maps.LatLngBounds();
    
        places.forEach(place => {
          if (place.geometry.viewport) {
            bounds.union(place.geometry.viewport)
          } else {
            bounds.extend(place.geometry.location)
          }
        });
    
        const nextMarkers = places.map(place => ({
          position: place.geometry.location,
        }));
    
        const nextCenter = _.get(nextMarkers, '0.position', this.state.center);
    
        this.setState({
          center: nextCenter
        });
    
        this.props.onSearchTermChange(this.state.center);
      }
    
      render() {
        return(
          <StandaloneSearchBox
            ref={this.onSearchBoxMounted.bind(this)}
            bounds={this.bounds.bind(this)}
            onPlacesChanged={this.onPlacesChanged.bind(this)}>
            <input
              type="text"
              placeholder="Search for restrooms"
              style={{
                boxSizing: `border-box`,
                border: `1px solid transparent`,
                width: `240px`,
                height: `32px`,
                padding: `0 12px`,
                borderRadius: `3px`,
                boxShadow: `0 2px 6px rgba(0, 0, 0, 0.3)`,
                fontSize: `14px`,
                outline: `none`,
                textOverflow: `ellipses`,
              }} />
          </StandaloneSearchBox>
        );
      }
    }
    
    export default withScriptjs(SearchBar);
    
  3. 地图.js

    import React, { Component } from 'react';
    import { withGoogleMap, GoogleMap, Marker } from 'react-google-maps';
    
    class Map extends Component {
      constructor() {
        super();
        this.state = {
          map: null
        }
      }
    
      mapMoved() {
        console.log('mapMoved: '+ JSON.stringify(this.state.map.getCenter()));
      }
    
      mapLoaded(map) {
        if(this.state.map !== null) {
          return;
        }
    
        console.log("here: " + JSON.stringify(this.props.center));
    
        this.setState({
          map: map
        });
      }
    
      render() {
        const markers = this.props.markers || []
        console.log("reload");
        return (
            <GoogleMap
              ref={this.mapLoaded.bind(this)}
              onDragEnd={this.mapMoved.bind(this)}
              defaultZoom={this.props.zoom}
              defaultCenter={this.props.center}>
              {markers.map((marker, index) => (
                  <Marker {...marker} />
                )
              )}
            </GoogleMap>
        );
      }
    }
    
    export default withGoogleMap(Map)
    
4

1 回答 1

0

仅基于快速浏览,我认为您可能需要将 componentWillReceiveProps() 添加到 Map 类,并在更新后的 lat 和 lng 值时使用 setState() 更新 this.state.map。

于 2018-02-27T12:23:48.047 回答