1

I'm trying to display some KML data on a map, using OpenLayers.

Nothing complex - but it's just not rendering.

Here's my javascript code

var map;

function init(element, kml) {
    map = new OpenLayers.Map(element, {
        projection: 'EPSG:3857',
        layers: [
            new OpenLayers.Layer.Google(
                'Google Streets', // the default
                { numZoomLevels: 20 }
            ),
            new OpenLayers.Layer.Vector('Kml data')
        ],
        center: new OpenLayers.LonLat(153.132, -26.987)
            // Google.v3 uses web mercator as projection, so we have to
            // transform our coordinates
            .transform('EPSG:4326', 'EPSG:3857'),
        zoom: 10
    });

    // Grab the features.
    var features = convertKmlToFeatures(kml);

    // Display it.
    map.layers[1].addFeatures(features);
}

function convertKmlToFeatures(kml) {
    var kmlFormat = new OpenLayers.Format.KML();
    return kmlFormat.read(kml);
}

Basically,

  • Create a map with two layers.
  • Convert the Kml to features.
  • Display the features on the map.

I just don't see what I've done wrong :(

Oh - on a side note, the KML data is fine, because when I tried it to visualise it on this website, it worked.

enter image description here

  • Is atleast the Google Maps Basemap visible? – Devdatta Tengshe May 22 '13 at 8:24
  • Yes - it's visible. and centers AND zoom's. when it loads the features, it moves to 0,0 and zooms right in :( – Pure.Krome May 22 '13 at 11:19
1

My guess is that you have to transform the geometry of the features read from the kml from 'EPSG:4326' to 'EPSG:3857'. Something like:

function convertKmlToFeatures(kml) {
    var kmlFormat = new OpenLayers.Format.KML();
    var features = kmlFormat.read(kml);
    for(var i=0, l=features.length;i<l; i++) {
       features[i].geometry.transform('EPSG:4326', 'EPSG:3857'); 
    } 
    return features;  
}

(if .transform() is in-place, never remember that)

| improve this answer | |
  • You sir, are a Scholar and a Gentleman! That was it!! (wish i got some error messages in the console why it didn't work). – Pure.Krome May 22 '13 at 11:24
  • Thank you! I guess it's difficult to give error messages, it should then be based on the fact that you are trying to add features outside of the map bounds. Always check coordinate systems in OpenLayers, it does not do any magic for you (might change in ol3?) – atlefren May 22 '13 at 11:51
  • 1
    and ... we have a new website working: geospatialconversions.azurewebsites.net thanks!!! – Pure.Krome May 22 '13 at 12:33

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.