google maps api v3 exporting kml file of current map

Omran picture Omran · May 18, 2012 · Viewed 9.2k times · Source

I have a google map component in my application that allows the user to draw polygons, lines, and marker. Now I want to implement a button that allows the user to export a kml file of the stuff that he/she draw in the map.

Any suggestion for the best approach to do so.

Your comments and contribution is highly appreciated

Answer

Tina CG Hoehr picture Tina CG Hoehr · May 19, 2012

I'll summarize my idea as storing coordinates as the user draws, then when the "Output KML" button is clicked, format the saved coordinate data and place it in a textarea to be copied (unless there's a way to prompt as a download?).

Here's how I save data when the user completes a drawing element:

http://jsfiddle.net/8bwG2/

(I don't know a good way of detecting edits.)

First, add event listeners for each drawing type (line, polygon, marker), to fire when it is complete. You need a separate event listener for each type. Here's one for Polylines, and each listener will return the type of drawing element that was just completed.

    google.maps.event.addDomListener(drawingManager, 'polylinecomplete', function(line) {
        path = line.getPath();
        document.getElementById("action").value += "#polyline\n";
        for(var i = 0; i < path.length; i++) {
          document.getElementById("action").value += path.getAt(i) + "\n";
        }
    });

I am placing the coordinates straight into a shared textarea but they should instead go into an array of arrays variable, with one variable for polygons, one for polylines and one for markers.

When reading from these internal variables, convert the Google Maps LatLngs to KML format long,lat,altitude. You will have to get creative with each element's name and description.

Finally, when the KML is requested, loop through the markers, line, and polygon variable to generate KML formatted elements, such as Point-coordinates, LineString, and Polygon-outerBoundaryIs