[GIS] Openlayers: Get Start and End Points of Line Vector Features

kmllineopenlayers-2vector

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..

Best Answer

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.