[GIS] How to center the map to a KML placemark with OpenLayers 3

javascriptkmlopenlayers

I'm using OpenLayers 3 to display my KML layer on the map.
My KML contains two placemarks, one contains a linestring of waypoints and the second one is a point, like this:

<kml xmlns="http://www.opengis.net/kml/2.2" 
xmlns:gx="http://www.google.com/kml/ext/2.2" 
xmlns:xal="urn:oasis:names:tc:ciq:xsdschema:xAL:2.0" 
xmlns:atom="http://www.w3.org/2005/Atom">
<Folder>
 <Placemark>
   <name>Asset 5</name>
    <description>
      Path
    </description>
   <Style>
   <LineStyle>
    <color>41FA7800</color>
    <width>2.5</width>
   </LineStyle>
  </Style>
 <LineString> 
   <extrude>0</extrude>
   <tessellate>1</tessellate>
   <altitudeMode>relativeToGround</altitudeMode>
  <coordinates>
    ... lots of coordinates ...
  </coordinates>
 </LineString>
 </Placemark>
<Placemark>
  <name>Current location</name>
  <description>Current location </description>
  <Point> <coordinates>50.1384717,11.2500542</coordinates> </Point>
</Placemark>
</Folder>
</kml>

I would like to center the map at the position of the second Point placemark.

How can I do this?

Best Answer

Create the vector layer:

var vector = new ol.layer.Vector({
   source: new ol.source.KML({
       projection: 'EPSG:3857',
       url: 'http://path/to/your/data.kml'
   })
});

Add it to the OpenLayer 3 map:

var map = new ol.Map({
    target: 'map',
    layers: [
        new ol.layer.Tile({
            source: new ol.source.OSM()
        }), vector
    ],
    view: view
});

And then wait until the layer is ready to access its second feature's coordinates and use them to center the view (borrowed from Layer loadstart & loadend events in OpenLayers 3):

var listenerKey = vector.getSource().on('change', function(e) {
    if (vector.getSource().getState() == 'ready') {
        view.setCenter(vector.getSource().getFeatures()[1].getGeometry().getCoordinates());
        view.setZoom(5);
        vector.getSource().unByKey(listenerKey); // Disconnect
    }
});

I've created this JSFiddle for reference.

Related Question