首页 > 解决方案 > 使用 Express 和 Node.js 的 Google Maps API

问题描述

我正在尝试使用带有 express/node 的谷歌地图 API 创建一个基本的网络应用程序。目前我的三个文件如下:

服务器.js

const express = require('express');
const bodyParser = require('body-parser');
const app = express()

app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs')

// Initialize and add the map
function initMap() {
    // The location of Uluru
    var uluru = {
      lat: -25.344,
      lng: 131.036
    };
    // The map, centered at Uluru
    var map = new google.maps.Map(
      document.getElementById('map'), {
        zoom: 4,
        center: uluru
      });
    // The marker, positioned at Uluru
    var marker = new google.maps.Marker({
      position: uluru,
      map: map
    });
  }

app.get('/', function (req, res) {
  res.render('index');
})

app.post('/', function (req, res) {
    res.render('index');
  })

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})

样式.css

#map {
    height: 400px; 
    width: 100%; 
   }

索引.html

<h3>My Google Maps Demo</h3>
<div id="map"></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=API&callback=initMap">
</script>

当我运行应用程序时,返回的错误是“initMap 不是函数”。我一直在网上阅读示例,但我尝试过的一切都没有奏效。我希望尽可能少地使用我的 HTML 文件中的 javascript。

标签: javascripthtmlnode.jsgoogle-mapsexpress

解决方案


你的代码没有问题

它工作正常,请检查以下内容:

解决方案:将initMap()函数应用于客户端 javascript 文件,而不是server.js

function initMap() {
    // The location of Uluru
    var uluru = {
        lat: -25.344,
        lng: 131.036
    };
    // The map, centered at Uluru
    var map = new google.maps.Map(
        document.getElementById('map'), {
            zoom: 4,
            center: uluru
        });
    // The marker, positioned at Uluru
    var marker = new google.maps.Marker({
        position: uluru,
        map: map
    });
}
#map {
    height: 400px; 
    width: 100%; 
}
<script async defer
        src="https://maps.googleapis.com/maps/api/js?key=_____&callback=initMap">
</script>


<h3>My Google Maps Demo</h3>
<div id="map"></div>

注意:切勿将您的 API 密钥分享给任何人!


推荐阅读