首页 > 解决方案 > 无法在 React Google Map 上使用 FitBounds

问题描述

即使对此有几个问题,我也无法在其中找到解决方案。原因如下:我从 npm 中的 react-google-maps 制作了一个 Google 地图组件。该组件的渲染显示:

render() {
return (this.state.skipRender && "Bad Addresses") || (
  <Map      
    google={this.props.google}
    initialCenter={this.state.center}
    bounds={this.state.bounds}
  >
    {this.displayMarkers()}
  </Map>
);

}

我想放置一个 fitBound,以使 displayMarkers 中生成的所有标记在视口中可见。但是我无处可以使用fitbounds。如果我把它作为属性的一部分,什么都不会发生。如果我尝试使用 map.fitBounds 它说“地图”是未定义的。我应该如何应用 fitBounds?

以防万一,这是 displayMarkers 函数:

  displayMarkers = () => {
return this.state.skipRender || this.state.addresses.map((address, index) => {
  return <Marker
    key={index}
    id={index}
    position={{
      lat: address.lat,
      lng: address.lng
    }}
    title={this.state.titles[index]}
  />
});

}

标签: reactjsgoogle-maps

解决方案


我猜你正在使用google-maps-reactlibrary,对吧?

如果是这样,如果传递了 prop ,组件会在内部Map调用Map.fitBounds方法。bounds

这是一个如何使标记在视口中可见的示例:

import React, { Component } from "react";
import { Map, Marker, GoogleApiWrapper } from "google-maps-react";

const locations = [
  { Id: 1, name: "Oslo", lat: 59.923043, lng: 10.752839 },
  { Id: 2, name: "Stockholm", lat: 59.339025, lng: 18.065818 },
  { Id: 3, name: "Copenhagen", lat: 55.675507, lng: 12.574227 },
  { Id: 4, name: "Berlin", lat: 52.521248, lng: 13.399038 },
  { Id: 5, name: "Paris", lat: 48.856127, lng: 2.346525 }
];

class MapExample extends Component {
  constructor(props) {
    super(props);
    this.state = {
      bounds: null
    };
    this.handleMapLoad = this.handleMapLoad.bind(this)
  }

  handleMapLoad() {
    const bounds = new this.props.google.maps.LatLngBounds();
    for (let loc of locations) bounds.extend({ lat: loc.lat, lng: loc.lng });
    this.setState({bounds:bounds});
  }

  render() {
    return (
      <Map
        onReady={this.handleMapLoad}
        className={"map"}
        google={this.props.google}
        zoom={5}
        initialCenter={{ lat: 48.1327673, lng: 4.1753323 }}
        bounds={this.state.bounds}
      >
        {locations.map((loc, i) => (
          <Marker key={i} position={{ lat: loc.lat, lng: loc.lng }} />
        ))}
      </Map>
    );
  }
}

export default GoogleApiWrapper({
  apiKey: "--your key goes here--"
})(MapExample);

注意:onReady地图加载后触发事件


推荐阅读