TransWikia.com

Loading a GPX file using OpenLayers 2

Geographic Information Systems Asked on December 31, 2020

I am trying to read a gpx file and add it as a layer to Open Layers. Here is my code snippet

 osMap = new OpenLayers.Map({
        div: "map",
        maxExtent: extent,
        resolutions: mapResolutions,
        units: "m",
        projection: "EPSG:27700",
        restrictedExtent: restrictedExtent                         
    });

    osMap.addLayer(new OpenLayers.Layer.XYZ(
        "Leisure",
        ['https://api2.ordnancesurvey.co.uk/mapping_api/v1/service/wmts?service=WMTS&request=GetTile&version=1.0.0&layer=Leisure%2027700&style=true&format=image%2Fpng&tileMatrixSet=EPSG%3A27700&tileMatrix=EPSG%3A27700%3A${z}&tileRow=${y}&tileCol=${x}' + key
        ]
    ));

    vectorLayer = new OpenLayers.Layer.Vector("MarkersTrail"); 
    osMap.addLayer(vectorLayer);     

    osMap.setCenter(new OpenLayers.LonLat(400000, 400000), 0);

    var layer;
    var path = "filename";

    if((layer = osMap.getLayer(path)) == null) 
    {
        var gpxLayer = new OpenLayers.Layer.Vector("gpx", {
            strategies: [new OpenLayers.Strategy.Fixed()],
            protocol: new OpenLayers.Protocol.HTTP({
                url:path + ".gpx",
                format: new OpenLayers.Format.GPX({
internalProjection: "EPSG:27700"
                    extractStyles: true,
                    extractAttributes: true,
                    maxDepth: 2
                })
            })
        });

        gpxLayer.id = path;
        gpxLayer.setVisibility(false, false);
        osMap.addLayer(gpxLayer);


    }
    layer = osMap.getLayer(path);
    if(obj.checked == true) 
    {
        layer.setVisibility(true, false);
    }
    else 
    {
        layer.setVisibility(false, false);
    }

However it is not displaying the layer? Think I’ve missed a trick here….

One Answer

Are there any CORS errors shown on the console log? OpenLayers 2 HTTP protocol frequently fails to load resources because it uses unnecessarily complex XHR requests which cause CORS preflight requests which most servers do not expect or handle. Preceding your code with a redefinition of the OpenLayers code responsible for the problem often helps.

OpenLayers.Request.issue = function(config) {        
    // apply default config - proxy host may have changed
    var defaultConfig = OpenLayers.Util.extend(
        this.DEFAULT_CONFIG,
        {proxy: OpenLayers.ProxyHost}
    );
    config = config || {};
    config.headers = config.headers || {};
    config = OpenLayers.Util.applyDefaults(config, defaultConfig);
    config.headers = OpenLayers.Util.applyDefaults(config.headers, defaultConfig.headers);
    // Unwanted code removed. DO NOT add the "X-Requested-With" header.

    // create request, open, and set headers
    var request = new OpenLayers.Request.XMLHttpRequest();
    var url = OpenLayers.Util.urlAppend(config.url, 
        OpenLayers.Util.getParameterString(config.params || {}));
    url = OpenLayers.Request.makeSameOrigin(url, config.proxy);
    request.open(
        config.method, url, config.async, config.user, config.password
    );
    for(var header in config.headers) {
        request.setRequestHeader(header, config.headers[header]);
    }

    var events = this.events;

    // we want to execute runCallbacks with "this" as the
    // execution scope
    var self = this;

    request.onreadystatechange = function() {
        if(request.readyState == OpenLayers.Request.XMLHttpRequest.DONE) {
            var proceed = events.triggerEvent(
                "complete",
                {request: request, config: config, requestUrl: url}
            );
            if(proceed !== false) {
                self.runCallbacks(
                    {request: request, config: config, requestUrl: url}
                );
            }
        }
    };

    // send request (optionally with data) and return
    // call in a timeout for asynchronous requests so the return is
    // available before readyState == 4 for cached docs
    if(config.async === false) {
        request.send(config.data);
    } else {
        window.setTimeout(function(){
            if (request.readyState !== 0) { // W3C: 0-UNSENT
                request.send(config.data);
            }
        }, 0);
    }
    return request;
};

For reprojection to EPSG:27700 you will need to specify internal projection:

            format: new OpenLayers.Format.GPX({
                internalProjection: "EPSG:27700",
                ...

It seems the workaround to use proj4 version 2 isn't compatible here and only proj4 version 1.1 will work.

Answered by Mike on December 31, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP