繁体   English   中英

使用Node.js中的Google Maps制作地图

[英]Making a map using google maps in node.js

我正在尝试通过调用我的JavaScript文件为我做一个在node.js中创建地图的工作。

require('./js/file.js')();
initMap();

这没有用,因为它在我的initMap()函数中给我一个错误,指出“未定义google”。 因此,我尝试要求api脚本本身:

require('https://maps.googleapis.com/maps/api/js?key=APIKEY&libraries=places')();
require('./public/js/graphs.js')();
initMap();

毫不奇怪,它也不起作用。 我怎样才能解决这个问题? 我尝试在javascript文件本身内部的map api中加载,但这需要jquery(也未定义),依此类推。

您正在尝试初始化专为浏览器而不是Node设计的Google Maps JS,因此这就是为什么您收到“未定义”响应的原因。

我通过使用PhantomJS进行了这项工作; 您可以在其中创建地图的地方创建一个“ html模板”,初始化地图,然后绘制所需绘制的内容,然后可以使用PhantomJS将其保存为PDF / Image。

有一个例子:

“ PhantomJS脚本”

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中设置了1500ms,这只是为了确保地图已加载并完成绘制(也许有更好的方法,但是它可以工作)

而您的imageMap.html就是您使用GMaps所做的一切,例如使用docs中的示例文件:

<!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 Maps API的Node.js客户端。

是由Google提供的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM