我正在嘗試使用作為 primereact 庫一部分的 GMap 組件,但我不斷收到此錯誤:
未處理的運行時錯誤 ReferenceError: google is not defined
我正在開發一個 next.js 應用程式,這是我從 primereact 庫復制/粘貼的簡單代碼:
import { GMap } from 'primereact/gmap';
const DealershipLocation = () => {
const options = {
center: {lat: 36.890257, lng: 30.707417},
zoom: 12
};
return (
<div>
<GMap options={options} style={{width: '100%', minHeight: '320px'}} />
</div>
)
}
export default DealershipLocation
uj5u.com熱心網友回復:
從 GMAP 展示中,您似乎沒有正確加載 Google Maps JS。
添加這些功能...key=XXX您的 Google 地圖密鑰在哪里
const loadGoogleMaps = (callback) => {
const existingScript = document.getElementById('googleMaps');
if (!existingScript) {
const script = document.createElement('script');
script.src = 'https://maps.google.com/maps/api/js?key=XXX';
script.id = 'googleMaps';
script.async = true;
script.defer = true;
document.body.appendChild(script);
script.onload = () => {
if (callback) callback();
};
}
if (existingScript && callback) callback();
};
const removeGoogleMaps = () => {
const mapScript = document.getElementById('googleMaps');
if (mapScript) {
mapScript.parentNode.removeChild(mapScript);
const head = document.getElementsByTagName('head')[0];
const scripts = head.getElementsByTagName('script');
for (let i = 0; i < scripts.length; i ) {
let script = scripts[i];
let src = script.src;
if (src.startsWith('https://maps.google.com/maps')) {
head.removeChild(script);
}
}
}
};
然后將其加載到 React Hook..
const [googleMapsReady, setGoogleMapsReady] = useState(false);
useEffect(() => {
loadGoogleMaps(() => {
setGoogleMapsReady(true);
});
return () => {
removeGoogleMaps();
}
}, []);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/489314.html
上一篇:谷歌地圖查看不同的位置
