Google Maps API 演示 - google 未定义
<p>我正在尝试实现Google Maps API,并且一直在关注官方的Demo。</p>
<p>我复制了代码,只做了一个更改:</p>
<pre class="brush:php;toolbar:false;">// Raises an error: Access to script at 'file:///D:/Desktop/Stuff/map-test/test.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, isolated-app, chrome-extension, chrome, https, chrome-untrusted.
<script type="module" src="./index.js"></script>
// Changed to this
<script src="./index.js"></script></pre>
<p>结果,我收到以下错误:</p>
<pre class="brush:php;toolbar:false;">ReferenceError: google is not defined at initMap</pre>
<p>我猜这是由于从脚本中删除了 <code>type="module"</code> 造成的?大多数人如何实现它,因为似乎您需要自己托管模块才能为此导入它?</p>
<p>我已将代码更改为以下内容,但这会引发警告。</p>
<pre class="brush:php;toolbar:false;"><script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API_KEY"></script>
// Warning: Google Maps JavaScript API has been loaded directly without a callback. This is not supported and can lead to race conditions and suboptimal performance. For supported loading patterns please see https://goo.gle/js-api-loading</pre>
<p>谢谢!</p>
<p>编辑:</p>
<p>我阅读了之前关于使用 HTTP 服务器托管文件的答案,我误解了他们的意思是托管 JS 文件。相反,您应该在本地托管 HTML 文件以进行测试,而不是直接打开 HTML 文件(即在文件资源管理器中双击它)。</p>
<p>所以使用 python3:</p>
<pre class="brush:php;toolbar:false;"># in the directory that contains index.html:
python3 -m http.server 8080</pre>
<p>访问 http://localhost:8080/index.html 对我有用。谢谢!</p>