Я пытаюсь использовать Electron.js для создания небольшого приложения и пытаюсь добавить к нему страницу карт Google. Я уже получил ключ API. Когда я запускаю приложение, оно ненадолго показывает изображение Карт Google, а затем выдает сообщение об ошибке: «Ой! Что-то пошло не так. Эта страница неправильно загрузила Карты Google. См. технические подробности в консоли JavaScript». Когда я открываю консоль, я вижу ошибку:

"security-warnings.ts:179 Electron Security Warning (Insecure Content-Security-Policy) This renderer process has either no Content Security
    Policy set or a policy with "unsafe-eval" enabled. This exposes users of
    this app to unnecessary security risks.

For more information and help, consult
https://electronjs.org/docs/tutorial/security.
This warning will not show up
once the app is packaged.
(anonymous) @ security-warnings.ts:179
Promise.then (async)
warnAboutInsecureCSP @ security-warnings.ts:172
logSecurityWarnings @ security-warnings.ts:295
loadHandler @ security-warnings.ts:312
async function (async)
loadHandler @ security-warnings.ts:311
load (async)
securityWarnings @ security-warnings.ts:315
(anonymous) @ init.ts:216
./lib/renderer/init.ts @ init.ts:217
__webpack_require__ @ bootstrap:19
(anonymous) @ bootstrap:83
(anonymous) @ bootstrap:83
NativeModule.compile @ internal/bootstrap/loaders.js:287
NativeModule.compileForPublicLoader @ internal/bootstrap/loaders.js:222
loadNativeModule @ internal/modules/cjs/helpers.js:23
Module._load @ internal/modules/cjs/loader.js:699
Module._load @ electron/js2c/asar.js:717
Module._load @ electron/js2c/asar.js:717
Module.runMain @ internal/modules/cjs/loader.js:1038
(anonymous) @ internal/main/run_main_module.js:17
js?key=MY_API_KEY&callback=initMap:56 Google Maps JavaScript API error: ApiNotActivatedMapError
https://developers.google.com/maps/documentation/javascript/error-messages#api-not-activated-map-error
_.od @ js?key=MY_API_KEY&callback=initMap:56
(anonymous) @ common.js:73
(anonymous) @ common.js:149
c @ common.js:67
(anonymous) @ AuthenticationService.Authenticate?1sfile%3A%2F%2F%2FUsers%2Fisaiahbell%2FProjects%2Fgeo-app%2Fmap.html&MY_API_KEY&callback=_xdc_._m2aezz&key=YOUR_API_KEY&token=54562:1"

Мой текущий код выглядит следующим образом:

Index.html

 <!DOCTYPE html>
    <html>
      <head>
        </head>
      <body>


        <center>
          <a href="map.html">Open Maps</a>
        </center>








         <script src="./render.js"></script>
      </body>
    </html>




    <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
    type="text/javascript"></script>

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8">


        <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
      </head>
      <body>

Map.html:

<!DOCTYPE html>

<html>

  <head>



    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Simple Markers</title>
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>



  </head>
  <body>
    <button><a href="index.html">Go Back</a><</button>
    <div id="map"></div>
    <script>

      function initMap() {
        var myLatLng = {lat: -25.363, lng: 131.044};

        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 4,
          center: myLatLng
        });

        var marker = new google.maps.Marker({
          position: myLatLng,
          map: map,
          title: 'Hello World!'
        });
      }
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY">
    </script>
  </body>
</html>
1
Isaiah_6200 21 Апр 2020 в 00:41
Я удалил ваш ключ API из вашего ответа. Пожалуйста, не делитесь закрытыми ключами API на общедоступных сайтах и ​​убедитесь, что вы ограничили их в соответствии с developers.google.com/maps/…
 – 
evan
23 Апр 2020 в 10:13

1 ответ

Обратите внимание, что вы получаете эту ошибку:

Ошибка Google Maps JavaScript API: ApiNotActivatedMapError https://developers.google. com/maps/documentation/javascript/error-messages#api-not-activated-map-error

Это означает, что вам необходимо включить JavaScript API. на вашем проекте.

Если после включения у вас возникают ошибки, связанные с CSP, которые препятствуют загрузке вашей карты, проверьте Как разрешить политике безопасности контента запускать внешний javascript из google api?

Надеюсь это поможет!

0
evan 23 Апр 2020 в 10:09