首页 > 解决方案 > 在 Node.js/Express 上加载 Google Maps API 简单地图

问题描述

我正在尝试创建一个在服务器端加载 Google Maps API 的 Web 应用程序,因为我想在其地图上加载标记。

以下是相关 Web 应用程序的项目结构: 项目文件结构

如果我在浏览器上加载 HTML 文件,地图就会显示在屏幕上。

但是,如果我在 node.js 上加载运行 app.js,我会得到一个几乎空白的屏幕。 几乎黑屏

甚至我自己也不确定是否要将 html 呈现为静态文件,因为它涉及到如此多的动态元素。

这是我的 css html 和 js 文件的样子。注意:出于安全目的,API 密钥不会显示。

应用程序.js

const express = require('express');

const port = 3000;
const path = require('path');

const app = express();

app.get('/', function(req,res) {
  res.sendFile(__dirname + '/index.html');
  //__dirname : It will resolve to your project folder.
});


//add the router
app.listen(port, () => console.log(`listening on port ${port}!`));

索引.html

<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title>CTA Bus Live</title>
  <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
  <link rel="stylesheet" type="text/css" href="./style.css" />
  <script src="./index.js"></script>
</head>

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

  <!-- Async script executes immediately and must be after any DOM elements used in callback. -->
  <script async defer src="https://maps.googleapis.com/maps/api/js?key=KEY&callback=initMap">

  </script>

  <script src="http://ctabustracker.com/bustime/api/v2/gettime?vid=4367&key=wGSShQesdeEhNFS92HF2BKDyS&format=json"></script> --
</body>

</html>

index.js

let map, infoWindows;

function initMap() {
  const styledMapType = new google.maps.StyledMapType(
    [{
      featureType: "poi",
      elementType: "labels",
      stylers: [{
        visibility: "off"
      }],
    }, ], {
      name: "Transit"
    }
  );

  map = new google.maps.Map(document.getElementById("map"), {
    center: {
      lat: 41.8774,
      lng: -87.6319
    },
    zoom: 15,
    mapTypeControlOptions: {
      mapTypeIds: ["roadmap", "satellite", "hybrid", "terrain", "styled_map"],
    },
  });

  var myLatlng = new google.maps.LatLng(41.831677, -87.625826);

  var marker = new google.maps.Marker({
    position: myLatlng,
    title: "CTA Green Line",
    icon: {url: "https://www.iconsdb.com/icons/preview/color/009B3A/circle-xxl.png",
    scaledSize: new google.maps.Size(15, 15)},
    optimized: false
  });

  // To add the marker to the map, call setMap();
  marker.setMap(map);


  map.mapTypes.set("styled_map", styledMapType);
  map.setMapTypeId("styled_map");

  const transitLayer = new google.maps.TransitLayer();

  if (map.getMapTypeId() === "styled_map") {
    transitLayer.setMap(map);
  }

  map.addListener("maptypeid_changed", () => {
    if (map.getMapTypeId() !== "styled_map") {
      transitLayer.setMap(null);
    }
    if (map.getMapTypeId() === "styled_map") {
      transitLayer.setMap(map);
    }
  });

}

样式.css

#map {
  height: 100%;
}

html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}

这就是我希望我的页面在节点上运行时的样子: 目标

标签: javascriptnode.jsexpressgoogle-mapsgoogle-maps-api-3

解决方案


推荐阅读