React and Google Maps with google-maps-react, cant get to API's methods

1.9k views Asked by At

Im using google-maps-react, and it works pretty good, but i just cant understand how can i work with Google Maps API's methods inside my component. Now i need to getBounds of rendered map, but cant find any way to do this. Here is the code, any help would be appreciated.

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);

Google Maps Api v 3.30.4

1

There are 1 answers

8
Daniel Andrei On BEST ANSWER

You could try and adapt your requirements to the following example here.

From what i can see a reference is returned using the onReady prop.

For example :

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);