Home > Back-end >  How to extract point coordinates of lines from MGLShapeSource in Mapbox Swift
How to extract point coordinates of lines from MGLShapeSource in Mapbox Swift

Time:08-09

I plot lines correctly on a Mapbox iOS map using a geojson files I have created. I read the geojson file and associate it to a shape like so:
shapeFromGeoJSON = try? MGLShape(data: jsonData, encoding: String.Encoding.utf8.rawValue)

Then I create a linesSource and a linesLayer and then I show the linesLayer on the map correctly:

linesSource = MGLShapeSource(identifier: "polyline", shape: shapeFromGeoJSON, options: nil)

linesLayer = MGLLineStyleLayer(identifier: "polyline", source: linesSource)

mapView.style?.addSource(linesSource)

mapView.style?.addLayer(linesLayer)

Inside the geojson file, each line is represented by a "geometry" with multiple "coordinates" of type "LineString".

I need to do some special processing that involves knowing all the coordinates of the points making the lines.

Question: how can I get all the multiple point coordinates of each LineString from linesSource?

Here's my geojson file for testing:

{ "features":

{
  "type": "Feature",
  "properties": {},
  "geometry": {
    "coordinates": [
      -9.316333,
      38.680709
    ],
    "type": "Point"
  },
  "id": "1234"
},
{
  "type": "Feature",
  "properties": {},
  "geometry": {
    "coordinates": [
      [
        -9.31687,
        38.680772
      ],
      [
        -9.317531,
        38.679794
      ],
      [
        -9.318001,
        38.679196
      ],
      [
        -9.318436,
        38.678612
      ],
      [
        -9.318592,
        38.678354
      ]
    ],
    "type": "LineString"

  },
  "id": "567"
},



{
  "type": "Feature",
  "properties": {},
  "geometry": {
    "coordinates": [
      -9.316057,
      38.680838
    ],
    "type": "Point"
  },
  "id": "89"
},



{
  "type": "Feature",
  "properties": {},
  "geometry": {
    "coordinates": [
      -9.316719,
      38.680715
    ],
    "type": "Point"
  },
  "id": "1011"
},




{
  "type": "Feature",
  "properties": {},
  "geometry": {
    "coordinates": [
      -9.315931,
      38.681066
    ],
    "type": "Point"
  },
  "id": "1213"
}

], "type": "FeatureCollection" }

CodePudding user response:

From my experiences with MapBox, not everything is easily user accessible. It might just be easiest to make a simple struct, decode the data into that, and access the coordinates from there.

  • Related