1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
/**
* External dependencies
*/
import { Component, createPortal } from '@wordpress/element';
export class InfoWindow extends Component {
componentDidMount() {
const { mapboxgl } = this.props;
this.el = document.createElement( 'DIV' );
this.infowindow = new mapboxgl.Popup( {
closeButton: true,
closeOnClick: false,
offset: {
left: [ 0, 0 ],
top: [ 0, 5 ],
right: [ 0, 0 ],
bottom: [ 0, -40 ],
},
} );
this.infowindow.setDOMContent( this.el );
this.infowindow.on( 'close', this.closeClick );
}
componentDidUpdate( prevProps ) {
if ( this.props.activeMarker !== prevProps.activeMarker ) {
this.props.activeMarker ? this.openWindow() : this.closeWindow();
}
}
render() {
// Use React portal to render components directly into the Mapbox info window.
return this.el ? createPortal( this.props.children, this.el ) : null;
}
closeClick = () => {
this.props.unsetActiveMarker();
};
openWindow() {
const { map, activeMarker } = this.props;
this.infowindow.setLngLat( activeMarker.getPoint() ).addTo( map );
}
closeWindow() {
this.infowindow.remove();
}
}
InfoWindow.defaultProps = {
unsetActiveMarker: () => {},
activeMarker: null,
map: null,
mapboxgl: null,
};
export default InfoWindow;
|