无法在React Google Map上使用FitBounds

时间:2019-12-03 13:23:08

标签: reactjs google-maps

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

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]}
  />
});

}

2 个答案:

答案 0 :(得分:0)

您将必须手动设置正确的centerzoom。为此,您可能需要使用utility function fitBounds

import { fitBounds } from 'google-map-react/utils';

const bounds = {
  nw: {
    lat: 50.01038826014866,
    lng: -118.6525866875
  },
  se: {
    lat: 32.698335045970396,
    lng: -92.0217273125
  }
};

const size = {
  width: 640, // Map width in pixels
  height: 380, // Map height in pixels
};

// use these to re-render your map
const {center, zoom} = fitBounds(bounds, size); 

答案 1 :(得分:0)

我猜您正在使用google-maps-react library,对吧?

如果是,则Map组件如果传递了Map.fitBounds属性,则调用bounds方法internally

以下是如何使标记在视口中可见的示例:

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事件