首页 > 解决方案 > 如何使用 google-maps-react 居中和放大多个标记?

问题描述

我发现这个堆栈溢出链接是用 vanilla javascript 完成的,但是它使用了我在google-maps-react API中看不到的方法,比如LatLngBoundsand bounds.extend(),但它确实有maps.fitbounds().

我是否错过了对 API 的误读,或者这些方法在 google-maps-react 上真的不存在。如果不是,那么我将如何在地图上的多个标记上进行居中和放大。

标签: javascriptreactjsgoogle-mapsgoogle-maps-api-3google-maps-react

解决方案


我认为 google-maps-react 没有本地方式来完成此操作,您必须直接通过onGoogleApiLoadedprop 使用 google maps api。

这个例子中的花絮这个例子

    // Fit map to its bounds after the api is loaded
const apiIsLoaded = (map, maps, places) => {
  // Get bounds by our places
  const bounds = getMapBounds(map, maps, places);
  // Fit map to bounds
  map.fitBounds(bounds);
  // Bind the resize listener
  bindResizeListener(map, maps, bounds);
};

class Main extends Component {
  constructor(props) {
    super(props);

    this.state = {
      places: [],
    };
  }

  componentDidMount() {
    fetch('places.json')
      .then((response) => response.json())
      .then((data) => this.setState({ places: data.results }));
  }

  render() {
    const { places } = this.state;
    return (
      <>
        {!isEmpty(places) && (
          <GoogleMap
            defaultZoom={10}
            defaultCenter={LOS_ANGELES_CENTER}
            yesIWantToUseGoogleMapApiInternals
            onGoogleApiLoaded={({ map, maps }) => apiIsLoaded(map, maps, places)}
          >
            {places.map((place) => (
              <Marker
                key={place.id}
                text={place.name}
                lat={place.geometry.location.lat}
                lng={place.geometry.location.lng}
              />
            ))}
          </GoogleMap>
        )}
      </>
    );
  }
}

export default Main;

推荐阅读