第一次点击

时间:2017-09-21 17:01:47

标签: javascript google-maps react-redux

我已经检查过并阅读了几篇关于这个问题的文章并尝试了一些事情,但似乎没有任何工作。问题是在第一次没有任何反应时点击标记。第二次点击它然后事件被触发。在4或5次点击之前infowindow没有显示,我不知道我做错了什么。 这不是一个更实际的问题。因为,我已经检查了所有的浏览器。 我使用下面的代码在我的地图中打开一个infowindow:

 import React, {Component, PropTypes} from 'react';
import {connect} from 'react-redux';
import _ from 'lodash';
import {
  withGoogleMap,
  GoogleMap,
  Marker,
  InfoWindow,
  TrafficLayer,
} from 'react-google-maps';
import {loadGodViewDrivers} from '../../../actions/driverActions';
import {loadGodViewBranches} from '../../../actions/branchActions';
import './OverviewMap.scss';

const actions = {
  loadGodViewDrivers,
  loadGodViewBranches,
};

const GoogleMapsContainer = withGoogleMap(props => {
  function getPosition(marker) {
    return {
      lat: marker.address
          ? marker.address.location.latitude
          : marker.location.latitude,
      lng: marker.address
          ? marker.address.location.longitude
          : marker.location.longitude,
    };
  }

  return (

      <GoogleMap
          ref={props.onMapLoad}
          defaultZoom={11}
          options={props.mapsOptions}
          onDragEnd={props.mapChanged}
          onZoomChanged={props.mapChanged}
          defaultCenter={props.mapCenter}
      >
        <TrafficLayer autoUpdate/>
        {typeof props.mapHolderRef !== 'undefined' &&
        _.size(props.branches) > 0 && (
            props.branches.map((it, i) => {
                  return (
                      <Marker
                          key={i}
                          position={getPosition(it)}                       
                          onClick={() => props.onMarkerClick(it)}
                          icon={'/img/merchant.png'}
                      >

                        {it.showInfo && (
                            <InfoWindow
                                onCloseClick={() => props.onMarkerClose(it)}>
                              {it.merchant ? (<div
                                  style={ {display: 'flex', alignItems: 'center'}}>
                                <div className="pull-left text-center"><img
                                    src={it.merchant.logo}
                                    className="img-circle" alt="Restaurant logo"
                                    width="90" height="90"/>
                                  <div style={ {height: '12px'} }></div>
                                  <div style={ {height: '20x'}}><span
                                      className={ it.merchant.suspended
                                          ? 'label label-danger'
                                          : 'label label-success'}>{ it.merchant.suspended
                                      ? 'suspended'
                                      : 'active'}</span>
                                  </div>
                                </div>
                                <div className="pull-right"
                                     style={ {
                                       paddingLeft: '15px',
                                       display: 'flex',
                                       flexDirection: 'column',
                                       alignItems: 'center',
                                     }}>
                                  <h4 className="text-center"
                                      style={{paddingBottom: '8px'}}>{it.name}<br/>
                                    <small>{it.address.firstLine}</small>
                                  </h4>
                                  <div><p style={{fontSize: '14px'}}>
                                    <span style={{
                                      backgroundColor: '#337ab7',
                                      border: '2px solid #2e6da4',
                                      fontSize: '15px',
                                      color: '#fff',
                                      display: 'inline-flex',
                                      alignItems: 'center',
                                      justifyContent: 'center',
                                      borderRadius: '50%',
                                      width: '32px',
                                      height: '32px',
                                      marginRight: '6px',
                                    }}><i
                                        className="fa fa-cutlery"></i></span><a
                                      href={`/merchants/${it.merchant._id}`}>{it.merchant.name}</a>
                                  </p><p style={{
                                    fontSize: '14px',
                                    marginBottom: '0',
                                  } }>
                                    <span
                                        style={{
                                          backgroundColor: '#337ab7',
                                          border: '2px solid #2e6da4',
                                          fontSize: '15px',
                                          color: '#fff',
                                          display: 'inline-flex',
                                          alignItems: 'center',
                                          justifyContent: 'center',
                                          borderRadius: '50%',
                                          width: '32px',
                                          height: '32px',
                                          marginRight: '6px',
                                        }}><i
                                        className="fa fa-phone"></i></span><a
                                      href={`tel:${it.phone}`}>{it.phone}</a></p>
                                  </div>
                                </div>
                              </div>) : <div className="text-center">No merchant
                                data</div>}
                            </InfoWindow>)}
                      </Marker>
                  );

                },
            )
        )}
        {typeof props.mapHolderRef !== 'undefined' &&
        _.size(props.drivers) > 0 && (
            props.drivers).map((it, i) => {
              if(it.available || (it.orderStatus && it.currentOrder && it.orderStatus !== null && it.currentOrder !== null))
              return (
                  <Marker
                      key={i * 2}
                      position={getPosition(it)}
                      onClick={() => props.onMarkerClick(it)}
                      onCloseClick={() => props.onMarkerClose(it)}
                      icon={it.orderStatus === 'en_route' ? '/img/driver_green.png' : it.orderStatus === 'waiting_pack' ? '/img/driver_yellow.png' : it.available ? '/img/driver_grey.png' : '/img/driver_red.png'}
                  >

                    {it.showInfo && (
                        <InfoWindow
                            onCloseClick={() => props.onMarkerClose(it)}>
                          <div style={ {display: 'flex', alignItems: 'center'}}>
                            <div className="pull-left text-center"><img
                                src={it.userPhoto}
                                className="img-circle" alt="User photo"
                                width="90" height="90"/>
                              <div style={ {height: '12px'} }></div>
                              <div style={ {height: '20x'}}><span
                                  className={ !it.available
                                      ? 'label label-danger'
                                      : 'label label-success'}>{ !it.available
                                  ? 'unavailable'
                                  : 'available'}</span>
                              </div>
                            </div>
                            <div className="pull-right"
                                 style={ {
                                   paddingLeft: '15px',
                                   display: 'flex',
                                   flexDirection: 'column',
                                   alignItems: 'center',
                                 }}>
                              <h4 className="text-center"
                                  style={{paddingBottom: '8px'}}><a
                                  href={`/drivers/${it._id}`}>{it.userName}</a>
                                <br/>
                                <small>{it.userEmail}</small>
                              </h4>
                              <div><p style={{fontSize: '14px'}}>
                                    <span style={{
                                      backgroundColor: '#337ab7',
                                      border: '2px solid #2e6da4',
                                      fontSize: '15px',
                                      color: '#fff',
                                      display: 'inline-flex',
                                      alignItems: 'center',
                                      justifyContent: 'center',
                                      borderRadius: '50%',
                                      width: '32px',
                                      height: '32px',
                                      marginRight: '6px',
                                    }}><i
                                        className="fa fa-cutlery"></i></span>
                                <a href={`/orders/${it.currentOrder}/`}>Current order</a>
                              </p><p style={{
                                fontSize: '14px',
                                marginBottom: '0',
                              } }>
                                    <span
                                        style={{
                                          backgroundColor: '#337ab7',
                                          border: '2px solid #2e6da4',
                                          fontSize: '15px',
                                          color: '#fff',
                                          display: 'inline-flex',
                                          alignItems: 'center',
                                          justifyContent: 'center',
                                          borderRadius: '50%',
                                          width: '32px',
                                          height: '32px',
                                          marginRight: '6px',
                                        }}><i
                                        className="fa fa-phone"></i></span><a
                                  href={`tel:${it.workPhone}`}>{it.workPhone}</a>
                              </p>
                              </div>
                            </div>
                          </div>
                        </InfoWindow>)}
                  </Marker>
              );
            },
        )}

      </GoogleMap>
  );
});
class OverviewMap extends Component {
  constructor(props) {
    super(props);

    this.state = {
      center: null,
    };

    this.handleRecenterClick = this.handleRecenterClick.bind(this);
    this.handleMapsRef = this.handleMapsRef.bind(this);
    this.mapChanged = _.debounce(this.mapChanged.bind(this), 500);

  }

  handleMapLoad = this.handleMapLoad.bind(this);

  handleMapLoad(map) {
    this._mapComponent = map;
    this.mapHolderRef = map;

    this.mapChanged();
  }

  mapChanged() {
    const bounds = this.mapHolderRef.getBounds();

    const ne = bounds.getNorthEast();
    const sw = bounds.getSouthWest();
    this.props.loadGodViewDrivers({
      nw: {lat: ne.lat(), lng: sw.lng()},
      se: {lat: sw.lat(), lng: ne.lng()},
    });

    this.props.loadGodViewBranches({
      nw: {lat: ne.lat(), lng: sw.lng()},
      se: {lat: sw.lat(), lng: ne.lng()},
    });

    this.setState({
      center: {
        lat: this.mapHolderRef.getCenter().lat(),
        lng: this.mapHolderRef.getCenter().lng(),
      },
    });
  }

  componentDidMount() {
    this.mapChanged();
    this.mapChangedInterval = setInterval(this.mapChanged, 2000);
  }

  componentWillUnmount() {
    clearInterval(this.mapChangedInterval);
  }

  getDefaultCenter() {
    return {
      lat: 29.234232862891145,
      lng: 47.947988063964885,
    };
  }

  handleRecenterClick() {
    const center = this.getDefaultCenter();

    this.setState({
      center: {
        lat: center.lat + Math.pow(10, -5),
        lng: center.lng,
      },
    });
  }

  handleMapsRef(mapHolder) {
    this.mapHolderRef = mapHolder;
    this.googleMaps = mapHolder && mapHolder.props.map;

    if (this.googleMaps) this.mapChanged();
  }

  handleMarkerClick = this.handleMarkerClick.bind(this);
  handleMarkerClose = this.handleMarkerClose.bind(this);

  handleMarkerClick(targetMarker) {
    this.setState({ 
       branches: this.props.branches.map(marker => {
        if (marker == targetMarker) {
          return {
            ...marker,
            showInfo: true,
          };
        }
        return marker;

      }),
      drivers: this.props.drivers.map(marker => {
        if (marker == targetMarker) {
          return {
            ...marker,
            showInfo: true,
          };
        }
        return marker;
      }),
    });
  }

  handleMarkerClose(targetMarker) {
    this.setState({
      branches: this.props.branches.map(marker => {
        if (marker == targetMarker) {
          return {
            ...marker,
            showInfo: true,
          };
        }
        return marker;
      }),
      drivers: this.props.drivers.map(marker => {
        if (marker == targetMarker) {
          return {
            ...marker,
            showInfo: false,
          };
        }
        return marker;
      }),

    });
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.branches !== nextProps.branches ||
        _.size(this.state.branches) === 0) {
      this.setState({
        branches: _.map(nextProps.branches, (marker, i) => {
          return {
            ...marker,
            showInfo: typeof this.state.branches !== 'undefined'
                ? typeof this.state.branches[i] !== 'undefined'
                    ? this.state.branches[i].showInfo
                    : false
                : false,
          };
        }),
      });
    }
    if (this.props.drivers !== nextProps.drivers ||
        _.size(this.state.drivers) === 0) {
      this.setState({
        drivers: _.map(nextProps.drivers, (marker, i) => {
            return {
              ...marker,
              showInfo: typeof this.state.drivers !== 'undefined'
                  ? typeof this.state.drivers[i] !== 'undefined'
                      ? this.state.drivers[i].showInfo
                      : false
                  : false,
            };
        }),
      });
    }
  }

  render() {
    const mapCenter = this.state.center || this.getDefaultCenter();
    const mapsOptions = {
      streetViewControl: true,
      mapTypeControl: true,
      signInControl: true,
    };

    return (
        <GoogleMapsContainer
            containerElement={
              <div style={{height: '100%'}}/>
            }
            mapElement={
              <div style={{height: '100%'}}/>
            }
            onMapLoad={this.handleMapLoad}
            mapCenter={mapCenter}
            mapsOptions={mapsOptions}
            mapChanged={this.mapChanged}
            mapHolderRef={this.mapHolderRef}
            mapRef={this.handleMapsRef}
            branches={this.state.branches}
            drivers={this.state.drivers}
            onMarkerClick={this.handleMarkerClick}
            onMarkerClose={this.handleMarkerClose}
        />
    );
  }
}
function mapStateToProps(state) {


  return {
    branches: state.branches.godView,
    drivers: state.drivers.godView,
  };

}
export default connect(mapStateToProps, actions)(OverviewMap);

上面的代码,在谷歌地图上的标记上加载时调用。在第一时间,首先通过ajax调用点击标记,infowindow的内容作为响应。在第二次单击时,infowindow将打开。下一次,点击加载infowindow的标记即可。 以前有人有过这个bug吗?有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

由于没有其他人在回答我的问题,我自己找到了: 我的错误是我在比较两个Javascript对象&#34; marker == targetMarker&#34;。 因此,只需将此行更新为marker == targetMarker._id&#34;而且运作良好。希望对于那些被这样的事情困扰的人来说会有所帮助。如果你想比较两个Javascripts对象,你需要使用一个特定的属性,就像我只是用id。