2

So... I have this script:

 <script>
        //Script1: Script de criação do mapa.    
        var map = new ol.Map({
             layers: [
                new ol.layer.Tile({
                    source: new ol.source.OSM()
                }),
              new ol.layer.Vector({
                    source: new ol.source.Vector({
                        url: 'data/geojson/countries.geojson',
                        format: new ol.format.GeoJSON()
                    })
                })
            ],
            target: 'map',
            controls: ol.control.defaults({
                attributionOptions: /** @type {olx.control.AttributionOptions} */ ({
                    collapsible: false
                })
            }),
            view: new ol.View({
                center: [-5462834.47, -3058929.70],
                zoom: 8
            })
        });
        //FIM SCRIPT1.

        //Script2: Script para exportar o mapa em visualização para uma imagem formato PNG
        var exportPNGElement = document.getElementById('export-png');

        if ('download' in exportPNGElement) {
            exportPNGElement.addEventListener('click', function (e) {
                map.once('postcompose', function (event) {
                    var canvas = event.context.canvas;
                    exportPNGElement.href = canvas.toDataURL('image/png');
                });
                map.renderSync();
            }, false);
        } else {
            var info = document.getElementById('no-download');
            /**
             * display error message
             */
            info.style.display = '';
        }
        //FIM SCRIPT2.

        //Script3: Criação das Camadas KML. Bairros, Zonas, Perimetros, etc.
        var vilanova = new OpenLayers.Layer.Vector("KML", {
            strategies: [new OpenLayers.Strategy.Fixed()],
            protocol: new OpenLayers.Protocol.HTTP({
                url: "../wp-content/uploads/2015/01/VILA-NOVA.kml",
                format: new OpenLayers.Format.KML({
                    extractStyles: true,
                    extractAttributes: true,
                    maxDepth: 2,
                    setVisibility: true
                })
            })
        });           
        //FIM SCRIPT3.

        //Script4: Ativa e desativa as camadas KML.                      
        function bairros(i, layername) {
            if (i.checked === true) {
                map.addLayer(eval(layername));
            }
            else {
                map.removeLayer(eval(layername));
            }
        }
        //FIM SCRIPT4.
    </script>

All I want to do is to show the KML layer and the export to PNG button. I have these two examples working properly apart. But when I try to merge them... they don't work at all.

The button still works (Export-PNG), but the KML layer does not. I have a checkbox to show and hide the "vilanova.kml" Every time I check the box to show the KML layer, the map freezes and when I uncheck it the map goes to wherever I dragged it before (when it was frozen).

Anyone already had a similar problem?

The KML layer example I got from another website. The "export to png" example/button I got from the OpenLayers Examples.


So... here's another script...

Everything is working. The KML layer can be shown and stuff... and I can draw polygons... All I want to do now is to export the map as a PNG.

<!DOCTYPE html>
<!--FUNCIONANDO!!!-->
<html>
<head><title>OpenLayers KML Example</title>
    <style>
        #map {
            height: 400px;
            width: 1000px;
        }
        .ol-attribution a {
            color: black;
        }            
    </style>
    <script src="http://www.openlayers.org/api/OpenLayers.js"></script>
    <script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ol3/3.4.0/ol.css" type="text/css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ol3/3.4.0/ol.js"></script>
</head>
<body>
    <br>      
    <div id="mydiv">
        <div class="container-fluid">

            <div class="row-fluid">
                <div class="span12">
                    <div id="map" class="map"></div>
                    <div id="no-download" class="alert alert-error" style="display: none">
                        This example requires a browser that supports the
                        <a href="http://caniuse.com/#feat=download">link download</a> attribute.
                    </div>
                    <a id="export-png" class="btn" download="map.png"><i class="icon-download"></i> Export PNG</a>
                </div>
            </div>
        </div>
        <form name="camadas">
            <input type="checkbox" class="camadas" name="vilanova" id="vilanova" onChange="bairros(this, 'vilanova')"/> Vila Nova            
        </form>            
        <div style="font-weight: bold">Camada de Edição</div>
        <select id="mapMode" name="mapMode" size="1" onchange="changeMapMode(this.value);">
            <option value="none" selected>Navegar pelo Mapa</option>
            <option value="polygon">Criar Polígonos</option>
            <option value="point">Criar Pontos</option>
            <option value="modify">Modificar Pontos/Poligonos ja criados</option>
            <!--<option value="point">Draw Point</option>-->
            <!--<option value="box">Draw Box</option>-->
            <!--<option value="circle">Draw Circle</option>-->
            <option value="select">Selecionar Objetos</option>
        </select>
        <input type="button" value="download" id="export-png" onClick="convertasbinaryimage()"/>     
    </div>    
    <script>
        map = new OpenLayers.Map("map"); 
        map.addLayer(new OpenLayers.Layer.OSM());
        var lonLat = new OpenLayers.LonLat(-5462834.47, -3058929.70)
                .transform(
                // new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
                   map.getProjectionObject() // to Spherical Mercator Projection
                );
        var zoom = 2;
        map.setCenter(lonLat, zoom);
        drawingLayer = new OpenLayers.Layer.Vector("Drawing layer");
        drawingLayer.events.on({
            'featureselected': function (feature) {
                updateFeatureTable(this.selectedFeatures);
            },
            'featureunselected': function (feature) {
                updateFeatureTable(this.selectedFeatures);
            }
        });
        map.addLayer(drawingLayer);

        drawingControls = {
            polygon: new OpenLayers.Control.DrawFeature(drawingLayer, OpenLayers.Handler.Polygon, {
                eventListeners: {
                    "featureadded": controlFeatureHandler
                }
            }),
            point: new OpenLayers.Control.DrawFeature(drawingLayer, OpenLayers.Handler.Point),
            modify: new OpenLayers.Control.ModifyFeature(drawingLayer, OpenLayers.Handler.dragComplete),
            select: new OpenLayers.Control.SelectFeature(
                    drawingLayer,
                    {
                        clickout: false, toggle: false,
                        multiple: false, hover: false,
                        toggleKey: "ctrlKey", // ctrl key removes from selection
                        multipleKey: "shiftKey", // shift key adds to selection
                        box: true
                    }
            )
        };

        for (var key in drawingControls) {
            map.addControl(drawingControls[key]);
        }

        var highlightCtrl = new OpenLayers.Control.SelectFeature(drawingLayer, {
            hover: true,
            highlightOnly: true,
            renderIntent: "temporary",
            eventListeners: {
                //beforefeaturehighlighted: report,
                featurehighlighted: report,
                featureunhighlighted: unReport
            }
        });
        map.addControl(highlightCtrl);
        highlightCtrl.activate();

        function report(e) {
            //OpenLayers.Console.log(e.type, e.feature.id);
            document.getElementById('highlighted').innerHTML = e.feature.id;
        }
        ;
        function unReport(e) {
            //OpenLayers.Console.log(e.type, e.feature.id);
            document.getElementById('highlighted').innerHTML = "";
        }
        ;

        function changeMapMode(value) {
            for (var key in drawingControls) {
                var control = drawingControls[key];
                if (value == key) {
                    control.activate();
                } else {
                    control.deactivate();
                }
            }
        }
        function controlFeatureHandler(event) {
        }

        function updateFeatureTable(featureList) {
            var wkt = new OpenLayers.Format.WKT();
            var table = "<table border='1'>";
            for (var key in featureList) {
                table += "<tr><td>";
                table += featureList[key].id;
                table += "</td><td>";
                table += wkt.write(featureList[key]);
                table += "</td></tr>";
            }
            table += "</table>";
            document.getElementById('featureTable').innerHTML = table;
        }

        //Declaração de Camadas KML
        var vilanova = new OpenLayers.Layer.Vector("KML", {
            strategies: [new OpenLayers.Strategy.Fixed()],
            protocol: new OpenLayers.Protocol.HTTP({
                url: "../wp-content/uploads/2015/01/VILA-NOVA.kml",
                format: new OpenLayers.Format.KML({
                    extractStyles: true,
                    extractAttributes: true,
                    maxDepth: 2,
                    setVisibility: true
                })
            })
        });

//Centro do mapa e zoom

        var lonLat = new OpenLayers.LonLat(-5462834.47, -3058929.70)
                .transform(
                //new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
                map.getProjectionObject() // to Spherical Mercator Projection
                );
        var zoom = 2;
        map.setCenter(lonLat, zoom);
        //Add a selector control to the kmllayer with popup functions
        var controls = {
            selector: new OpenLayers.Control.SelectFeature(kmllayer, {onSelect: createPopup, onUnselect: destroyPopup})
        };
        function createPopup(feature) {
            feature.popup = new OpenLayers.Popup.FramedCloud("pop",
                    feature.geometry.getBounds().getCenterLonLat(),
                    null,
                    '<div class="markerContent">' + feature.attributes.description + '</div>',
                    null,
                    true,
                    function () {
                        controls['selector'].unselectAll();
                    }
            );
            //feature.popup.closeOnMove = true;
            map.addPopup(feature.popup);
        }

        function destroyPopup(feature) {
            feature.popup.destroy();
            feature.popup = null;
        }

        map.addControl(controls['selector']);
        controls['selector'].activate();

        function bairros(i, layername) {
            if (i.checked === true) {
                map.addLayer(eval(layername));
            }
            else {
                map.removeLayer(eval(layername));
            }
        }

        //Add the vector layer
        var polygonLayer = new OpenLayers.Layer.Vector("My Polygon");
        //Add the layer to map
        map.addLayer(polygonLayer);

        //Drawing controls
        drawControls = {
            polygon: new OpenLayers.Control.DrawFeature(polygonLayer, OpenLayers.Handler.Polygon)
        };
        //Add the drawing control to polygon
        map.addControl(drawControls.polygon);

        //Activate the drawing control
        drawControls.polygon.activate();

        //You can add the select control to the polygons
        //This is not a necessary step
        var options = {
            hover: false
        };
        var select = new OpenLayers.Control.SelectFeature(polygonLayer, options);
        select.onSelect = function (e) {
            var mapProjv = map.getProjectionObject();
            var epsg4326v = new OpenLayers.Projection("EPSG:4326");
            var verticesNative = e.geometry.getVertices();
            var verticesLatLon = [];
            var verticesStr = "";
            for (var x in verticesNative) {
                verticesLatLon.push(verticesNative[x].clone().transform(mapProjv, epsg4326v));
                verticesStr += verticesLatLon[x].toShortString() + ";";
            }
            document.getElementById("verticesStr").innerHTML = "Area Vertices: " + verticesStr;
        }
        //Add the select control to the map
        map.addControl(select);
        //Activate the select control
        select.activate();

        var exportPNGElement = document.getElementById('export-png');

        if ('download' in exportPNGElement) {
            exportPNGElement.addEventListener('click', function (e) {
                map.once('postcompose', function (event) {
                    var canvas = event.context.canvas;
                    exportPNGElement.href = canvas.toDataURL('image/png');
                });
                map.renderSync();
            }, false);
        } else {
            var info = document.getElementById('no-download');
            /**
             * display error message
             */
            info.style.display = '';
        }
    </script>
</body>
</html>

And now... can anyone help me?

You guys can test it here: http://www.jourdan.org.br/geojourdan-teste/

1

Checking your application I found a problem in your function bairros. The second parameter is a string (the layer name) for the map.addLayer you have to pass the vector layer object not the name.

<form name="camadas">
    <input type="checkbox" class="camadas" name="vilanova" id="vilanova" onChange="bairros(this, 'vilanova')"/> Vila Nova
    <input type="checkbox" class="camadas" name="vilalenzi" id="vilalenzi" onChange="bairros(this, 'vilalenzi')"/> Vila Lenzi
    <input type="checkbox" class="camadas" name="vilalalau" id="vilalalau" onChange="bairros(this, 'vilalalau')"/> Vila Lalau
    <input type="checkbox" class="camadas" name="vilabaependi" id="vilabaependi" onChange="bairros(this, 'vilabaependi')"/> Vila Baependi
</form>

Remove the single quotes in the function call:

<form name="camadas">
    <input type="checkbox" class="camadas" name="vilanova" id="vilanova" onChange="bairros(this, vilanova)"/> Vila Nova
    <input type="checkbox" class="camadas" name="vilalenzi" id="vilalenzi" onChange="bairros(this, vilalenzi)"/> Vila Lenzi
    <input type="checkbox" class="camadas" name="vilalalau" id="vilalalau" onChange="bairros(this, vilalalau)"/> Vila Lalau
    <input type="checkbox" class="camadas" name="vilabaependi" id="vilabaependi" onChange="bairros(this, vilabaependi)"/> Vila Baependi
</form>

In function bairros no need for eval:

    function bairros(i, layername) {
        if (i.checked === true) {
            map.addLayer(layername);
        }
        else {
            map.removeLayer(layername);
        }
    }

You had better to use jQuery to separate HTML and Javascript and $(document).ready(....) to define your event handlers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.