Accessing map link with React-google-maps v6 +

The newest changes to react-google-maps

appear to have removed the property mapHolderRef

to access the map instance. Looking at the new component changes, it looks like they are referencing internal constant references to the context, but it looks like they shouldn't be used / easily accessible.

Before the newest version, I was able to do something like below to add a custom control to the map:

paintControl(props) {
  const { rendered } = this.state;
  const position = props.position || google.maps.ControlPosition.TOP_CENTER;
  const map = props.mapHolderRef.getMap(); // This no longer works
  const controlElement = React.createElement(props.customControl, { map, ...props });

  ReactDOM.render(controlElement, this.customControlDiv);
  this.customControlDiv.style.zIndex = this.props.zIndex || 1;

  if (!rendered) {
    this.setState({ rendered: true }, () => {
      map.controls[position].push(this.customControlDiv);
    });
  }
}

      

In version 6.0, there were notes mentioning that this property is mapHolderRef

no longer available through props, but instead of context. I tried to get this to work but didn't seem to figure it out.

I am currently using a callback onMapLoad

to get the reactive map instance, but getting the actual google map link seems to be missing. I was able to get a useful link by running:

const map = props.mapHolderRef.context.__SECRET_MAP_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;

      

But it seems really noisy and wrong. It also creates multiple controls instead of maintaining one, so something doesn't work. Not sure if there is something in the new docs that I missed, or if it just isn't available in the new version.

Has anyone had any luck that custom controls or components work with the new version react-google-maps

?

Thank you for your help!

+3


source to share


2 answers


There doesn't seem to be a perfect solution for this even in v7.2, but there is a list of constants introduced since 7.0 that more elegantly refer to deprecated references:

import { MAP } from 'react-google-maps/lib/constants



See this Github commment - it was approved by the owner of the repo.

+1


source


To add to Max's answer, this is how I ended up with my code using v7.2.0:



import { MAP } from 'react-google-maps/lib/constants';

export default class CustomControl extends Component {
  static contextTypes = { [MAP]: PropTypes.object };

  ...

  // this.context[MAP] returns the google map instance object
  if (this.context[MAP]) {
    const map = this.context[MAP];
    map.controls[position].push(this.customControlDiv);
  }

      

+2


source







All Articles