javascript - 使用 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。
解决方案
你的代码没有问题
它工作正常,请检查以下内容:
解决方案:将
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 密钥分享给任何人!
推荐阅读
- azure - Azure DevOps:为什么在创建新服务连接时未显示我的订阅?
- r - r Shiny:将 dateInput 与 shinjs::toggleState 一起使用时无法解决错误
- c# - 我将如何解析文本文件中的某个值?
- c++ - round() 函数产生一个奇怪的数字
- mongodb - MongoDB 只返回嵌套的对象数组
- javascript - 如何在反应js中获取具有相同属性名称的数组中输入标签的值
- linux - Circle CI如何部署到ssh - 错误无法建立真实性
- python - SyntaxError: invalid character in identifier -- 尽管几乎可以肯定没有不允许的字符
- algorithm - 是否可以限制线性分区问题中的部分大小?
- javascript - 如何在 Jquery 中创建窗帘淡出效果?