Can OpenLayers parse GPX data which is stored as a string in a javascript variable?

1.7k Views Asked by At

I have a map site using OpenLayers, which imports and displays GPX data using the following code:

var lgpx = new OpenLayers.Layer.GML(gpxtracktitle, gpxfileaddress, {

  format: OpenLayers.Format.GPX,

  style: {strokeColor: plmapvars.colourarray[i%7], strokeWidth: 5, strokeOpacity: 0.7},

  projection: new OpenLayers.Projection("EPSG:4326")
});

map.addLayer(lgpx);

I'm looking for a way to display gpx data which, rather than being stored as a file, is saved as a string in a javascript variable:

var gpxstring ="<?xml ... </gpx>"

I've tried passing the string into the code above as a data uri, without success. Is OpenLayers capable of parsing GPX from a string in the way I'm attempting to do it?

Thanks in advance for any help.

1

There are 1 best solutions below

1
On

Maybe there is an easier way, but here you go:

You already know about OpenLayers.format.GPX [docs]. It has a read method, which accepts an XML document and returns an array of features. You can then add those feature to a layer.

How to parse the XML string and create an XML document is described in How to create and use a XML document object properly considering browser compatibility?