1

I'm trying hard to get start and end of lines from a vector. The line vector is loaded from a kml-file. For now, I tried to iterate over features in the vector and grab the start point and put it in a markers array, and then add to the map, but without success. The console.log shows me that the markers array is of length 0..

This is what I tried so far (live):

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta charset="utf-8"/>
    <title>OPEN TRAILS</title>
    <link rel="stylesheet" href="defaultstyle.css" type="text/css" />
    <style type="text/css">
        html, body: {
            height: 100%;
            width: 100%;
            position: relative;
        }
        .olControlAttribution {
            bottom: 3px;
        }
    </style>
    <script src="http://dev.openlayers.org/releases/OpenLayers-2.13.1/lib/OpenLayers.js"></script>
  </head>

  <body style="margin: 0;">
        <div id="map"></div>
        <div id="output-id"></div>
    </div>

    <script type="text/javascript">

        OpenLayers.Util.onImageLoadError = function() { this.style.display="none";}

        var map = new OpenLayers.Map( 'map' );
        var osm = new OpenLayers.Layer.OSM({numZoomLevels: 12});

        //default styles for vector layers
        var styleTrails = new OpenLayers.Style({
                /*label: "${name}",
                fontColor: "#909090",
                fontSize: "12px",
                fontFamily: "Verdana",
                fontWeight: "bold",*/
                strokeColor: "#F8D71C",
                strokeWidth: 4,
                strokeColor: "#F62700",
                strokeOpacity: 0.6,
                cursor: "pointer"
            })


        var KMLtrails = new OpenLayers.Layer.Vector("KML", {
            styleMap: new OpenLayers.StyleMap({
                "default": styleTrails,
                // selected style
                "select": {
                    strokeColor: "#1F5AFF",
                    cursor: "pointer"
                    }
                }),
            projection: map.displayProjection,
            strategies: [new OpenLayers.Strategy.Fixed()],
            protocol: new OpenLayers.Protocol.HTTP({
                url: "Trails.kml",
                format: new OpenLayers.Format.KML({
                    extractStyles: false, 
                    extractAttributes: true,
                    maxDepth: 2,
                })
            })
        });

        KMLtrails.events.on({
            featureselected: function(event) {
                var feature = event.feature;
                var name = feature.attributes.name;
                var desc = feature.attributes.description;
                var output = "<span style='font-family:Troika; font-size:24px;'>-- Info --</br></span>" + desc;
                document.getElementById("output-id").innerHTML = output;
                map.zoomToExtent(event.feature.geometry.getBounds(), closest=false);
            },
            featureunselected: function(event) { 
                document.getElementById("output-id").innerHTML = null;
            } 
        }); 

        var select = new OpenLayers.Control.SelectFeature(KMLtrails);
        map.addControl(select);
        select.activate();

        function StartMarkers() {       
            var features = KMLtrails.features;
            var size = new OpenLayers.Size(21,25);
            var markers = new OpenLayers.Layer.Markers( "Markers" );
            var icon = new OpenLayers.Icon('http://www.openlayers.org/dev/img/marker.png', size);
            for( var i = 0; i < features.length; i++ ) {
                var startPoint = features[i].geometry.components[0];
                markers.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(startPoint.x, startPoint.y), icon));
                }   
            return markers; 
        }

        var Markers = StartMarkers();
        console.log(Markers);
        map.addLayers([KMLtrails, Markers, osm]);

        KMLtrails.events.register("loadend", KMLtrails, function (e) {
            map.zoomToExtent(KMLtrails.getDataExtent());
        }); 
  </script>
  </body>
</html>

PS: This is a closed and rephrased previous question, which obviously didn't gain any attention..

1

You call StartMarkers before you add your KMLtrails layer to the map. KMLtrails.features is empty because it hasn't been loaded. If you set a breakpoint at var feature = event.feature; in your featureselected function you will see the features are loaded.

I'd suggest setting Markers to StartMarkers after you've loaded the KMLtrails and osm layers.

  • Thanks @Dave Lowther, I already tried this (see updated source of the live example). I also tried to put the StartMarker function within the registering of the KMLtrails loadend - but still no success.. – Kay Apr 28 '14 at 14:07
  • Hmm. I see from your updated live example that KMLtrails still isn't loaded when called, but when I set a breakpoint in the function registered for loadend and I go to the console KMLtrails.features has the features there. Can you update your live example to call StartMarkers in the loadend? – Dave Lowther Apr 29 '14 at 14:56
  • I've put the call to the loadend and now I also add the layer to the map here.. the log tells me the array was filled, at least partly - strangely some of the points have LonLat set to NA. However, the markers are not rendered.. – Kay Apr 29 '14 at 19:53
  • 1
    Here (gimoya.bplaced.net/Openlayers/Trails/map_exp_3.html) I tried it with getVertices(nodes=true), which actually works within the function registered for loadend of KMLtrails - However, I can't add the marker layer to the map inside this function. And when defining Markers outside it won't work either because the layer hasn't loaded when called.. – Kay Apr 30 '14 at 9:53
  • 1
    Finally got it - thanks @Dave Lowther! I just needed to make the variable markers global! – Kay Apr 30 '14 at 11:17
0

Here's the working script:

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta charset="utf-8"/>
    <title>OPEN TRAILS</title>
    <link rel="stylesheet" href="defaultstyle.css" type="text/css" />
    <style type="text/css">
        html, body: {
            height: 100%;
            width: 100%;
            position: relative;
        }
        .olControlAttribution {
            bottom: 3px;
        }
    </style>
    <script src="http://dev.openlayers.org/releases/OpenLayers-2.13.1/lib/OpenLayers.js"></script>
  </head>

  <body style="margin: 0;">
        <div id="map"></div>
        <div id="output-id"></div>
    </div>

    <script type="text/javascript">

        OpenLayers.Util.onImageLoadError = function() { this.style.display="none";}

        var map = new OpenLayers.Map( 'map' );
        var osm = new OpenLayers.Layer.OSM({numZoomLevels: 12});

        //default styles for vector layers
        var styleTrails = new OpenLayers.Style({
                /*label: "${name}",
                fontColor: "#909090",
                fontSize: "12px",
                fontFamily: "Verdana",
                fontWeight: "bold",*/
                strokeColor: "#F8D71C",
                strokeWidth: 4,
                strokeColor: "#F62700",
                strokeOpacity: 0.6,
                cursor: "pointer"
            })


        var KMLtrails = new OpenLayers.Layer.Vector("KML", {
            styleMap: new OpenLayers.StyleMap({
                "default": styleTrails,
                // selected style
                "select": {
                    strokeColor: "#1F5AFF",
                    cursor: "pointer"
                    }
                }),
            projection: map.displayProjection,
            strategies: [new OpenLayers.Strategy.Fixed()],
            protocol: new OpenLayers.Protocol.HTTP({
                url: "Trails.kml",
                format: new OpenLayers.Format.KML({
                    extractStyles: false, 
                    extractAttributes: true,
                    maxDepth: 2,
                })
            })
        });

        KMLtrails.events.on({
            featureselected: function(event) {
                var feature = event.feature;
                var name = feature.attributes.name;
                var desc = feature.attributes.description;
                var output = "<span style='font-family:Troika; font-size:24px;'>-- Info --</br></span>" + desc;
                document.getElementById("output-id").innerHTML = output;
                map.zoomToExtent(event.feature.geometry.getBounds(), closest=false);
            },
            featureunselected: function(event) { 
                document.getElementById("output-id").innerHTML = null;
            } 
        }); 

        var select = new OpenLayers.Control.SelectFeature(KMLtrails);
        map.addControl(select);
        select.activate();

        var markers = new OpenLayers.Layer.Markers( "Markers" );
        var size = new OpenLayers.Size(10,10);      

        function StartMarkers(layer) {      
            var features = layer.features;
            for( var i = 0; i < features.length; i++ ) {    
                var singleLine = features[i].geometry.components[0];
                var endPts = singleLine.getVertices(nodes = true);  //if nodes = true is set only start and end points will be returned..
                console.log(i);
                console.log(features[i].attributes.name);
                console.log(singleLine);
                markers.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(endPts[0].x, endPts[0].y), new OpenLayers.Icon('http://gimoya.bplaced.net/Openlayers/Icons/pin.png', size)));
                markers.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(endPts[1].x, endPts[1].y), new OpenLayers.Icon('http://gimoya.bplaced.net/Openlayers/Icons/pin.png', size)));
                }
            }

        KMLtrails.events.register("loadend", KMLtrails, function (e) {
            map.zoomToExtent(KMLtrails.getDataExtent());
            markers = StartMarkers(KMLtrails);
        }); 

        console.log(markers);

        map.addLayers([KMLtrails, osm, markers]); 

  </script>
  </body>
</html>

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.