【问题标题】:How to add custom controls on google map?如何在谷歌地图上添加自定义控件?
【发布时间】:2020-07-20 06:42:11
【问题描述】:

我正在使用 google-maps-react 库,我想在 google 地图上添加自定义控件,如按钮、输入元素等。请看我想要的图像。

【问题讨论】:

    标签: reactjs google-maps google-maps-react


    【解决方案1】:

    google-map-react 是一个基于一小部分 Google Maps API 编写的组件。它允许你在谷歌地图上渲染任何 React 组件。它是完全同构的,可以在服务器上渲染。此外,即使未加载 Google Maps API,它也可以在浏览器中呈现地图组件。它使用内部可调整的悬停算法 - 地图上的每个对象都可以悬停。

    在简单的情况下,您只需将 lat 和 lng 属性添加到 GoogleMapReact 组件的任何子组件。

    import GoogleMapReact from 'google-map-react';
     
    const AnyReactComponent = ({ text }) => <div>{text}</div>;
     
    class SimpleMap extends Component {
      static defaultProps = {
        center: {
          lat: 59.95,
          lng: 30.33
        },
        zoom: 11
      };
     
      render() {
        return (
          // Important! Always set the container height explicitly
          <div style={{ height: '100vh', width: '100%' }}>
            <GoogleMapReact
              bootstrapURLKeys={{ key: /* YOUR KEY HERE */ }}
              defaultCenter={this.props.center}
              defaultZoom={this.props.zoom}
            >
              <AnyReactComponent
                lat={59.955413}
                lng={30.337844}
                text="My Marker"
              />
            </GoogleMapReact>
          </div>
        );
      }
    }
     
    export default SimpleMap;
    
    

    【讨论】:

    • 但是如果我们拖动地图组件也会随着地图一起拖动。我需要应该固定位置的组件。并且组件位置不应依赖于地图经纬度坐标。
    最近更新 更多