Reputation: 3115
I am using a jsonp request to a server which is returning a string containing the geometry of a multiline vector. This looks like this (I've truncated it a little):
MULTILINESTRING((-0.61122 44.88987,-0.61108 44.88961,-0.6109 44.88926))
In Open Layers 3, when I usually create a vector feature I provide a string containing the geometry using the following code:
var vectorFeature = new ol.Feature({
geometry: new ol.geom.MultiLineString([[-0.11151,21.24112],[-0.11151,81.24112]])
});
Notice the difference in the formatting of the strings. Is there a way in Open Layers 3 of quickly reformatting the response from the jsonp request to allow me to quickly create a new vector feature based on this data, or am I going to have to parse the string and add the [] formatting myself?
Edit:
If I use the object returned from the JSONP request as an argument in MultiLineString directly (as follows):
var vectorFeature = new ol.Feature({
geometry: new ol.geom.MultiLineString(data.geometry)
});
then if I attempt to retrieve the co-ordinates of the object using:
console.log(vectorFeature.getGeometry().getCoordinates());
I get Array[ Array[1], Array[1], Array[1]... ]
Which isn't correct, and to me points towards the incorrect formatting of the supposedly geoJSON object?
Edit 2
The object being returned from the JSON request turned out to be WKT and not geoJSON which explains the difficulties.
Upvotes: 0
Views: 694
Reputation: 2786
The reply looks like WKT to me, isn’t it? OpenLayers have support for it directly.
Upvotes: 0
Reputation: 28638
In my opinion, using a regex would be a good solution in this case:
var string = 'MULTILINESTRING((-0.61122 44.88987,-0.61108 44.88961,-0.6109 44.88926))',
matches = string.match(/(\-?\d+(\.\d+)?)\s(\-?\d+(\.\d+)?)+/g),
results = [];
matches.forEach(function (match) {
results.push(match.split(' '));
});
Returns results
as a nested array object:
[
["-0.61122","44.88987"],
["-0.61108","44.88961"],
["-0.6109","44.88926"]
]
Working example on Plunker: http://plnkr.co/edit/mEjuaoPqWM0Zy6Y0RHER?p=preview
A sidenote, the string you get returned from the server isn't GeoJSON:
MULTILINESTRING((-0.61122 44.88987,-0.61108 44.88961,-0.6109 44.88926))
A proper GeoJSON MultiLineString geometry would look like this:
{
"type": "MultiLineString",
"coordinates": [
[[100.0, 0.0], [101.0, 1.0]],
[[102.0, 2.0], [103.0, 3.0]]
]
}
Reference specification: http://geojson.org/geojson-spec.html#id6
Upvotes: 1