React中google-map-react的API密钥无法传入请求URL问题
解决google-map-react无法传入API密钥的问题
以下是几个排查和修复的关键点:
修复import语法错误
你的代码里import语句少了闭合引号和分号,这会导致组件无法正确加载,进而使用默认的占位符密钥。把代码改成:import GoogleMapReact from 'google-map-react';移除手动引入的Google Maps脚本
如果你在HTML文件(比如public/index.html)里手动加了类似<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY_HERE"></script>的标签,赶紧删掉。google-map-react会自动加载带正确密钥的API脚本,手动引入会覆盖组件的配置。确保容器有宽高
地图组件需要明确的宽高才能正常渲染,给外层容器设置样式:<div style={{ height: '100vh', width: '100%' }}> <GoogleMapReact {/* 你的其他属性 */} /> </div>更新组件版本
运行npm update google-map-react把组件更到最新稳定版,旧版本可能存在配置传递的bug。检查API密钥权限
确认你的API密钥已经启用了「Google Maps JavaScript API」,并且在Google Cloud控制台里设置了正确的访问限制(比如允许当前开发域名),否则即使密钥正确也会报错。
修复后的完整代码示例:
import GoogleMapReact from 'google-map-react'; const defaultMapSettings = { center: [42.00, -95.00], zoom: 3 }; const MyMap = () => ( <div style={{ height: '100vh', width: '100%' }}> <GoogleMapReact bootstrapURLKeys={{ key: "你的实际API密钥" }} defaultCenter={defaultMapSettings.center} defaultZoom={defaultMapSettings.zoom} yesIWantToUseGoogleMapApiInternals /> </div> ); export default MyMap;
内容的提问来源于stack exchange,提问作者LuckyPierre
相关产品推荐
相关产品推荐

