|
| 1 | +import React, { useRef, useEffect } from 'react'; |
| 2 | + |
| 3 | +function createPopupClass() { |
| 4 | + function Popup({ position, content, map }) { |
| 5 | + this.position = position; |
| 6 | + this.containerDiv = content; |
| 7 | + this.setMap(map); |
| 8 | + google.maps.OverlayView.preventMapHitsAndGesturesFrom(this.containerDiv); |
| 9 | + } |
| 10 | + |
| 11 | + Popup.prototype = Object.create(google.maps.OverlayView.prototype); |
| 12 | + |
| 13 | + Popup.prototype.onAdd = function () { |
| 14 | + this.getPanes().floatPane.appendChild(this.containerDiv); |
| 15 | + }; |
| 16 | + |
| 17 | + Popup.prototype.onRemove = function () { |
| 18 | + if (this.containerDiv.parentElement) { |
| 19 | + this.containerDiv.parentElement.removeChild(this.containerDiv); |
| 20 | + } |
| 21 | + }; |
| 22 | + |
| 23 | + Popup.prototype.draw = function () { |
| 24 | + var divPosition = this.getProjection().fromLatLngToDivPixel(this.position); |
| 25 | + var display = |
| 26 | + Math.abs(divPosition.x) < 4000 && Math.abs(divPosition.y) < 4000 |
| 27 | + ? 'block' |
| 28 | + : 'none'; |
| 29 | + |
| 30 | + if (display === 'block') { |
| 31 | + this.containerDiv.style.left = divPosition.x + 'px'; |
| 32 | + this.containerDiv.style.top = divPosition.y + 'px'; |
| 33 | + } |
| 34 | + if (this.containerDiv.style.display !== display) { |
| 35 | + this.containerDiv.style.display = display; |
| 36 | + } |
| 37 | + }; |
| 38 | + |
| 39 | + return Popup; |
| 40 | +} |
| 41 | + |
| 42 | +const CustomPopup = ({ map, position, children }) => { |
| 43 | + const containerEl = useRef(null); |
| 44 | + useEffect(() => { |
| 45 | + const pos = new google.maps.LatLng(position.lat, position.lng); |
| 46 | + const Popup = createPopupClass(); |
| 47 | + const popup = new Popup({ |
| 48 | + position: pos, |
| 49 | + content: containerEl.current, |
| 50 | + map, |
| 51 | + }); |
| 52 | + }); |
| 53 | + return ( |
| 54 | + <div |
| 55 | + style={{ position: 'absolute' }} |
| 56 | + className="custom-popup" |
| 57 | + ref={containerEl} |
| 58 | + > |
| 59 | + {children} |
| 60 | + </div> |
| 61 | + ); |
| 62 | +}; |
| 63 | + |
| 64 | +export default CustomPopup; |
0 commit comments