Search code examples
javascriptnode.jsgoogle-earth-plugin

KML generated with javascript


Is there are any ways to generate KML for Google Earth with java script via node.js? Now I hava apache with PHP for that. Would be nice to have everything in one server.

I am quit new on js, if there are any axamples or something... I would appreciate it.


Solution

  • Yes you can! Doing so is actually quite easy. Node.js doesn't handle files the same way PHP does, Node.JS will serve the client the files. There are tons of template systems available for node.JS for you to use. Here is an example of a KML server using some basic techniques.

    //required to create the http server
    var http = require('http');
    //use EJS for our templates
    var ejs = require('ejs');
    //required so we can read our template file
    var fs = require('fs')
    
    //create a http server on port 8000
    http.createServer(function (req, res) {
    //tell the client the document is XML
    res.writeHead(200, {'Content-Type': 'text/xml'});
    //read our template file 
    fs.readFile('template.ejs', 'utf8', function (err, template) {
    //render our template file with the included varables to change
    var content = ejs.render(template,{
        name:"test name",
        description:"this is the description",
        coordinates:"-122.0822035425683,37.42228990140251,0"
    });
    //write the rendered template to the client
    res.write(content);
    res.end()
    }).listen(8000);
    
    console.log('Server listening at at http://localhost:8000/');
    

    And our template.ejs would look like this:

    <?xml version="1.0" encoding="UTF-8"?>
     <kml xmlns="http://www.opengis.net/kml/2.2">
       <Placemark>
         <name><%=name%></name>
         <description><%=description%></description>
         <Point>
           <coordinates><%=coordinates%></coordinates>
         </Point>
       </Placemark>
     </kml>
    

    In reality you would want to use something like connect or express. It sounds like you are pretty new to Node.JS, definitely spend some going through some of the introduction material.

    Happy Coding!