2

我正在使用 google-maps-react,它工作得很好,但我无法理解如何在我的组件中使用 Google Maps API 的方法。现在我需要获取渲染地图的边界,但找不到任何方法来做到这一点。这是代码,任何帮助将不胜感激。

import React from 'react';
import {Map, InfoWindow, Marker, GoogleApiWrapper} from 'google-maps-react';

const GOOGLE_MAPS_JS_API_KEY='AIzaSyB6whuBhj_notrealkey';


class GoogleMap extends React.Component {
constructor() {

    this.state = {
        zoom: 13
    }

    this.onMapClicked = this.onMapClicked.bind(this);
    this.test = this.test.bind(this);
}

onMapClicked (props) {
    if (this.state.showingInfoWindow) {
        this.setState({
            showingInfoWindow: false,
            activeMarker: null
        })
    }
}

test(google) {
// Here i tried a lot of ways to get coords somehow
    console.log(google.maps.Map.getBounds())
}

render() {
    const {google} = this.props;

    if (!this.props.loaded) {
        return <div>Loading...</div>
    }

    return (
        <Map className='google-map'
            google={google}
            onClick={this.onMapClicked}
            zoom={this.state.zoom}
            onReady={() => this.test(google)}
            >
        </Map>
        );
    }
}

export default GoogleApiWrapper({
apiKey: (GOOGLE_MAPS_JS_API_KEY)
})(GoogleMap);

谷歌地图 API v 3.30.4

4

1 回答 1

2

您可以尝试将您的要求调整为此处的以下示例。

从我可以看到使用onReady道具返回参考。

例如 :

import React from 'react';
import {Map, InfoWindow, Marker, GoogleApiWrapper} from 'google-maps-react';

const GOOGLE_MAPS_JS_API_KEY='AIzaSyB6whuBhj_notrealkey';


class GoogleMap extends React.Component {
constructor() {

    this.state = {
        zoom: 13
    }

    this.onMapClicked = this.onMapClicked.bind(this);
    this.handleMapMount = this.handleMapMount.bind(this);
}

onMapClicked (props) {
    if (this.state.showingInfoWindow) {
        this.setState({
            showingInfoWindow: false,
            activeMarker: null
        })
    }
}

handleMapMount(mapProps, map) {
    this.map = map;

    //log map bounds
    console.log(this.map.getBounds());
}

render() {
    const {google} = this.props;

    if (!this.props.loaded) {
        return <div>Loading...</div>
    }

    return (
        <Map className='google-map'
            google={google}
            onClick={this.onMapClicked}
            zoom={this.state.zoom}
            onReady={this.handleMapMount}
            >
        </Map>
        );
    }
}

export default GoogleApiWrapper({
apiKey: (GOOGLE_MAPS_JS_API_KEY)
})(GoogleMap);
于 2017-09-11T10:21:25.577 回答