首页 > 解决方案 > GoogleMap ReactJS:如何将状态值传递到 googlemap 的默认中心

问题描述

我目前正在研究https://tomchentw.github.io的 Google Map ReactJS ,我使用它是因为它是推荐的。

问题:

我有一定的疑问和问题。

为什么我不能将lat lng的状态值传递给谷歌地图的默认中心属性。我传递的道具没有价值,这就是为什么它变成灰色框..,如何将道具的值传递给defaultCenter?

图片

谷歌地图代码:

    const google = window.google

const MyMapComponent = compose(
  withProps({
    googleMapURL: "https://maps.googleapis.com/maps/api/js?&v=3.exp&libraries=geometry,drawing,places&key=AIzaSyDWCz4V5r29GxcGZKNtFzE9v4gOSnKVMYA",
    loadingElement: <div style={{ height: `100%` }} />,
    containerElement: <div style={{ height: `400px` }} />,
    mapElement: <div style={{ height: `100%` }} />,

  }),
  withHandlers({
    onMarkerClustererClick: () => (markerClusterer) => {
      const clickedMarkers = markerClusterer.getMarkers()
      console.log(`Current clicked markers length: ${clickedMarkers.length}`)
      console.log(clickedMarkers)
    },
  }),
  withScriptjs,
  withGoogleMap
)(props =>

      <GoogleMap
    defaultZoom={8}
    defaultCenter={{lat: parseFloat(props.lat_value_props), lng: parseFloat(props.lang_value_props) }}
    //defaultCenter={{lat:53.569967, lng:-113.393261}}
>

{props.markers.map(marker => (

    <Marker
        key={marker.id}
        position={{ lat: parseFloat(marker.store_lat), lng: parseFloat(marker.store_long) }}
    />

))}

</GoogleMap>
);

JSX:

    export default class FindStore extends Component {


      constructor(props) {
        super(props);

        this.state = {
          text:'',
          city:'',
          store_details:[],
          searchTerm: '',
          lat_value:'',
          lng_value:'',
          markers: [],

        }

        this.searchUpdated = this.searchUpdated.bind(this)
      }

      componentDidMount() {

        const id = this.props.match.params.id;
        axios.get('/api/find_store_location/' + id).then(response => {
            this.setState({
                markers: response.data,
                lat:response.data[0].store_lat,
                long:response.data[0].store_long,
            })

             console.log(this.state.lat_value);
             console.log(this.state.lng_value);

        }).catch(error => console.log(error));

        axios.get('/api/store_details').then(response => {
            this.setState({

              store_details:response.data

            })
           }).catch(error => console.log(error.response));
      }


      //store details oveflow leftside
    render() {

      const filteredEmails = this.state.store_details.filter(createFilter(this.state.searchTerm, KEYS_TO_FILTERS))
      return (

        <div>

          <div className="header">
              <div className="jumbotron">
                  <h1>Store Directory</h1>
              </div>
          </div>
          <br/><br/><br/>

          <div className="container">
            <div className="row">
              <div className="col-md-5">
                <form method="get" onSubmit={this.SubmitFilterStore}>
                  <div className="form-group">
                    <label htmlFor="exampleSelect1">Select City</label>
                    <select value={this.state.city} className="form-control" id="exampleSelect1">
                      <option readOnly={true} selected={true} >Choose City</option>
                      <option value="Winnipeg">Winnipeg</option>
                      <option value="Edmonton">Edmonton</option>
                      <option value="Calgary">Calgary</option>
                    </select>
                  </div>
                  <div className="input-group mb-3" id="text_search">

                    <SearchInput className="search-input" onChange={this.searchUpdated} />

                    <br/> <br/>
                    <div style={{overflowY:'scroll', height:'500px'}}>
                      {filteredEmails.map(store => {

                        if(store.image == "")
                        {
                          return (
                            <div className="store" key={store.id}>
                              <div className="card" style={{width: '18rem' }}>
                                  <div className="container">
                                  <br/>
                                    <p>No Store Image Uploaded</p>
                                  </div>
                                  <div className="card-body">
                                     <div id="store-description">
                                     <label>{store.branch_name}</label><br/> 
                                      <label>{store.store_type}</label><br/> 
                                      <label>{store.store_contactnumber}</label><br/> 
                                      <label>{store.store_businesshour}</label>
                                      <br/><br/>
                                      <Link to={'/find-store-location/'+store.id}><button className="btn">Direction <i className="fas fa-directions"></i> </button></Link>
                                     </div>
                                  </div>
                                </div>      
                                <br/>    
                            </div>
                          )
                        }
                        else
                        {
                          return (
                            <div className="store" key={store.id}>
                              <div className="card" style={{width: '18rem' }}>
                                  <div className="container">
                                  <br/>
                                  <img src={"/storage/"+store.image}
                                    height="120" 
                                  className="img-responsive"></img>

                                  </div>
                                  <div className="card-body">
                                      <div id="store-description">
                                        <label>{store.branch_name}</label><br/> 
                                        <label>{store.store_type}</label><br/> 
                                        <label>{store.store_contactnumber}</label><br/> 
                                        <label>{store.store_businesshour}</label>
                                        <br/><br/>
                                        <Link to={'/find-store-location/'+store.id}><button className="btn">Direction <i className="fas fa-directions"></i> </button></Link>
                                      </div>

                                  </div>
                                </div>      
                                <br/>    
                            </div>
                          )
                        }

                    })}
                    </div>
                  </div>
                </form>  
              </div>         
              <div className="col-md-7">


                  <MyMapComponent 
                markers={this.state.markers}  
                lat_value_props={this.state.lat_value}
                lang_value_props={this.state.lng_value}

             />


              </div>
            </div>


          </div>
        </div>


      )
    }

    searchUpdated (term) {
      this.setState({searchTerm: term})
    }

}

标签: reactjsgoogle-maps

解决方案


错误是因为 MyMapComponent 不是 React.Component ,因此 this.state 不存在。

解决方案是将 latlng 与标记数据一起发送到地图组件。

改成

<MyMapComponent 
    markers={this.state.markers}  
    latlng={this.state.latlng}
/>

<GoogleMap
    defaultZoom={8}
    defaultCenter={props.latlng}
>

推荐阅读