The newest changes to react-google-maps seem to have removed the mapHolderRef property to access the map instance. Looking at the new component changes, it looks like they call internal constant context references, but it doesn't seem like those should be used/are easily exposed.
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);
});
}
}
There was notes in the 6.0 release mentioning this mapHolderRef property is no longer accessible through props, but through context instead. I have tried getting that to work, but can't seem to figure it out.
I am currently using the onMapLoad callback to get the react map instance, but getting to the actual google map reference seems to be missing. I have been able to get a usable reference by doing:
const map = props.mapHolderRef.context.__SECRET_MAP_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
But that seems really janky and incorrect. It's also creating multiple controls instead of maintaining the one, so something is off there. Not sure if there's something in the new docs that I missed or if this simply isn't available in the new version.
Has anyone had luck getting custom controls or components to work with the new react-google-maps version?
Thanks for your help!
To add to Max's answer, this is how I ended up getting it to work in 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);
}
It seems that there is no ideal solution to this even in v7.2, but there are a list of constants introduced as of 7.0 that link to the deprecated references in a more elegant way:
import { MAP } from 'react-google-maps/lib/constants
See this Github commment -- it was endorsed by repo owner.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With