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" 
   <name>Asset 5</name>
    ... lots of coordinates ...
  <name>Current location</name>
  <description>Current location </description>
  <Point> <coordinates>50.1384717,11.2500542</coordinates> </Point>

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

How can I do this?


1 Answer 1


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') {
        vector.getSource().unByKey(listenerKey); // Disconnect

I've created this JSFiddle for reference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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