реагировать-google-карты увеличить карту в круг - PullRequest
0 голосов
/ 20 мая 2019

Это в основном вопрос о «переводе» JS в JSX.

У меня есть картаact-google-maps, которая содержит маркер и круг вокруг этого маркера:

Компонент карты:

export class Map extends Component {
  render() {
    const GoogleMapInstance = withGoogleMap(props => (
      <GoogleMap
        defaultCenter = { { lat: parseFloat(this.props.lat), lng: parseFloat(this.props.lng) } }
        defaultZoom = { 16 }
        defaultOptions={{ styles: mapStyles }}
      >
        <Marker position={{ lat: parseFloat(this.props.lat), lng: parseFloat(this.props.lng) }}/>
        <Circle center={{ lat: parseFloat(this.props.lat), lng: parseFloat(this.props.lng) }} radius={parseFloat(this.props.accuracy)} options={{ fillColor: 'red', strokeColor: 'red' }}/>
      </GoogleMap>
    ))
    return (
      <div>
        <GoogleMapInstance
          containerElement={ <div style={{ height: '600px', width: '100%' }}/> }
          mapElement={ <div style={{ height: '100%' }}/> }
        />
      </div>
    )
  }
}

Я бы хотел, чтобы карту масштабировали так, чтобы круг занимал около 50% карты. Я понимаю, используя Javascript API, я могу просто сделать:

map.fitBounds(circle.getBounds())

Но я не уверен, как интегрировать это с JSX, который у меня есть ...

Ответы [ 2 ]

0 голосов
/ 23 мая 2019

Действительно, вы можете получить доступ к собственным объектам Google Map и Circle с помощью Ref и манипулировать ими.Но когда дело доходит до получения экземпляра карты, предпочтите Карта idle событие более componentDidMount() метод жизненного цикла, чтобы гарантировать, что карта готова, например:

handleMapIdle() {
   const map = this.map.current; //get Google Map instance
   //...
}

, где

 <GoogleMap
        ref={this.map}
        onIdle={this.handleMapIdle}
        ...
      >
      ...
 </GoogleMap>

Вот модифицированный компонент карты:

class Map extends Component {
  constructor(props) {
    super(props);
    this.map = React.createRef();
    this.circle = React.createRef();
    this.handleMapIdle = this.handleMapIdle.bind(this);
    this.idleCalled = false;
  }

  handleMapIdle() {
    if (!this.idleCalled) {
      const bounds = this.circle.current.getBounds();
      this.map.current.fitBounds(bounds);
      this.idleCalled = true;
    }
  }

  render() {
    const GoogleMapInstance = withGoogleMap(props => (
      <GoogleMap
        ref={this.map}
        defaultCenter={{
          lat: parseFloat(this.props.lat),
          lng: parseFloat(this.props.lng)
        }}
        defaultZoom={this.props.zoom}
        onIdle={this.handleMapIdle}
      >
        <Marker
          position={{
            lat: parseFloat(this.props.lat),
            lng: parseFloat(this.props.lng)
          }}
        />
        <Circle
          ref={this.circle}
          center={{
            lat: parseFloat(this.props.lat),
            lng: parseFloat(this.props.lng)
          }}
          radius={parseFloat(this.props.accuracy)}
          options={{ fillColor: "red", strokeColor: "red" }}
        />
      </GoogleMap>
    ));
    return (
      <div>
        <GoogleMapInstance
          containerElement={<div style={{ height: "600px", width: "100%" }} />}
          mapElement={<div style={{ height: "100%" }} />}
        />
      </div>
    );
  }
}

Демо

0 голосов
/ 20 мая 2019

Вы, вероятно, хотите сделать что-то вроде этого:

export class Map extends Component {
  constructor(props) {
    super(props)
    this.map = React.createRef()
    this.circle = React.createRef()
  }

  componentDidMount() {
    if (this.map && this.circle) {
      const bounds = this.circle.current.getBounds()
      this.map.current.fitBounds(bounds)
    }
  }

  render() {
    const GoogleMapInstance = withGoogleMap(props => (
      <GoogleMap
        defaultCenter = { { lat: parseFloat(this.props.lat), lng: parseFloat(this.props.lng) } }
        defaultZoom = { 16 }
        defaultOptions={{ styles: mapStyles }}
        ref={this.map}
      >
        <Marker position={{ lat: parseFloat(this.props.lat), lng: parseFloat(this.props.lng) }}/>
        <Circle ref={this.circle} center={{ lat: parseFloat(this.props.lat), lng: parseFloat(this.props.lng) }} radius={parseFloat(this.props.accuracy)} options={{ fillColor: 'red', strokeColor: 'red' }}/>
      </GoogleMap>
    ))
    return (
      <div>
        <GoogleMapInstance
          containerElement={ <div style={{ height: '600px', width: '100%' }}/> }
          mapElement={ <div style={{ height: '100%' }}/> }
        />
      </div>
    )
  }
}

refs создает способ доступа к узлам GoogleMap и Circle, а componentDidMount - это ловушка жизненного цикла, которая позволяет запускать вызов fitBounds, когда компонент Map впервые отображается в ДОМ.

...