访问 Javascript 中的数据数组时遇到问题

Trouble with accessing array of data in Javascript

我正在尝试编写一个小型网络应用程序,它将使用 Google 的地图 JavaScript API 在地图上绘制一些位置。使用 API 进行得很顺利,但我正在尝试操纵他们的示例代码,但我无法使数据数组工作,除非它是使用 Map 初始化函数声明的。我一直在挖掘我对 Javascript 变量访问不了解的地方,但我无法弄清楚。理想情况下,我想将数据数组放在一个单独的 <script> 标记中,以便我可以从另一个文件加载它,但如果将数据放在同一 [=] 函数的正上方,我什至无法使数据工作12=] 标签。

我这里是代码的简化版本,我无法开始工作。它不会 运行 因为我从 API 的调用中删除了我的密钥,但如果需要它来找到问题我也可以给出它。

<html>
<head>
 <style>
  html, body {
   height: 100%;
   margin: 0;
   padding: 0;
  }
  #map {
   height: 100%;
   width: 100%;
  }
 </style>
</head>
<body>

<div id="map"></div>

// <script src="...">
// where I really want to load let locations = .... from a file
// </script>

<script>

  // where i tried to move let locations = .... without success

  function initMap() {
 const map = new google.maps.Map(document.getElementById("map"), {
  zoom: 2.7,
  center: new google.maps.LatLng(18,0)
 });

 let locations = [
  {
   name: 'MJ Cave',
   position: new google.maps.LatLng(47.517869, 19.036026)
  }, {
   name: 'Protec Tulum',
   position: new google.maps.LatLng(20.216557, -87.460052)
  }, {
   name: 'Giraffe Manor',
   position: new google.maps.LatLng(-1.375528, 36.744634)
  }
 ];

 function placeMarker( loc ) {
  const marker = new google.maps.Marker({
   position : loc.position,
   map : map
  });
 }
  
 // ITERATE ALL LOCATIONS. Pass every location to placeMarker
 locations.forEach( placeMarker );
  }
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=MYKEY&callback=initMap">    
</script>
</body>
</html>

问题已解决。

initMap() 函数中取出 new google.maps.latlng() 调用是问题所在,因为显然在代码运行时不一定定义该数据类型。将location位置对象改为由两个数字组成的数组定义,然后在函数中将它们做成一个google.maps.latlng。现在按需要工作。对于 postarity,这是我更改的代码:

<script>
 let locations = [
  {
  name: 'MJ Cave',
  position: [47.517869, 19.036026]
  }, {
  name: 'Protec Tulum',
  position: [20.216557, -87.460052]
  }, {
  name: 'Giraffe Manor',
  position: [-1.375528, 36.744634]
  }
 ];
</script>

<script type="text/javascript">

 function initMap() {
  const infowindow = new google.maps.InfoWindow();
  const map = new google.maps.Map(document.getElementById("map"), {
   zoom: 2.7,
   center: new google.maps.LatLng(18,0)
  });

  function placeMarker( loc ) {
   const marker = new google.maps.Marker({
    position : { lat: loc.position[0], lng: loc.position[1]},
     icon: icons[loc.type].icon,
    map : map
   });
  
  // ITERATE ALL LOCATIONS. Pass every location to placeMarker
  locations.forEach( placeMarker );
 }
</script>