我正在尝试通过调用我的javascript文件为我创建一个映射.js。
require('./js/file.js')();
initMap();
这不起作用,因为它在我的 initMap() 函数中给了我一个错误"谷歌未定义"。因此,我尝试要求 api 脚本本身:
require('https://maps.googleapis.com/maps/api/js?key=APIKEY&libraries=places')();
require('./public/js/graphs.js')();
initMap();
不出所料,这也不起作用。我该如何解决这个问题?我尝试在javascript文件本身的map api中加载,但这需要jquery,它也没有定义,等等。
您正在尝试初始化专为浏览器设计的Google Maps JS,而不是为Node设计的,因此这就是您获得"未定义"响应的原因。
我通过使用PhantomJS完成了这项工作;你创建一个"html模板",在那里你有你的地图,初始化地图,然后绘制你必须绘制的任何内容,你可以用PhantomJS将其保存为PDF/图像。
有一个例子:
"幻影JS脚本"
var page = require('webpage').create();
var system = require('system');
var args = system.args;
var fs = require('fs');
page.paperSize = {
format: 'A4',
orientation: 'portrait',
margin: '0mm'
};
var path = args[1];
var code = args[2];
page.open(path + '/imageMap.html', function(status) {
page.dpi = 96.0;
status = status.trim();
console.log(status);
if(status === "success") {
var title = page.evaluate(function(code) {
window.generateMap(code);
return true;
}, code);
setTimeout(function(){
page.render(path + '/img/' + code + '.png');
phantom.exit();
}, 1500);
}else{
phantom.exit(1);
}
});
如您所见,我在 setTimeout 中给出了 1500 毫秒,它只是为了确保地图已加载并完成绘制(也许有更好的方法,但是,它有效)
而你的imageMap.html就是你用GMaps做的任何事情,比如使用文档中的示例文件:
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
html, body {
width: 100%;
height: 100%;
margin:0px;
paddin:0px;
}
#map_canvas{
width:600px;
height: 445px;
}
.gm-style-cc {
display:none;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
async defer></script>
</body>
</html>
我希望这对某人有所帮助。
jQuery和其他前端库在nodejs中的工作方式不同。 您需要查看Google地图API的nodejs客户端。
这个是由谷歌提供的。