Peter R
Peter R

Reputation: 3516

How to parse GeoJSON to a type in Dart/Flutter

I have JSON like this coming from my server:

        {
          "coordinates": [
            [
              [
                -122.41251225499991,
                37.78047851100007
              ],
              [
                -122.42194124699989,
                37.77303605000009
              ],
              ...trimmed...
              [
                -122.41251225499991,
                37.78047851100007
              ]
            ]
          ],
          "crs": {
            "properties": {
              "name": "EPSG:4326"
            },
            "type": "name"
          },
          "type": "Polygon"
        }

I want to parse this on my server, but I'm not sure how to do that. I've found two Dart libs that work with GeoJSON:

geojson https://pub.dev/packages/geojson geojson_vi https://pub.dev/packages/geojson_vi

Both of those only have parsing from string functions, but I have a map. What's the best way to parse something like this in Dart/Flutter?

Upvotes: 0

Views: 3310

Answers (2)

Kartik Malhotra
Kartik Malhotra

Reputation: 257

You can convert map to string and use geojson Package to parse the GeoJson Data.

Upvotes: 0

M.M.Hasibuzzaman
M.M.Hasibuzzaman

Reputation: 1151

Do mean this?

class GetJsonData{
    GetJsonData({
        this.coordinates,
        this.crs,
        this.type,
    });

    List<List<List<double>>> coordinates;
    Crs crs;
    String type;

    factory GetVehicleInfo.fromJson(Map<String, dynamic> json) => GetVehicleInfo(
        coordinates: List<List<List<double>>>.from(json["coordinates"].map((x) => List<List<double>>.from(x.map((x) => List<double>.from(x.map((x) => x.toDouble())))))),
        crs: Crs.fromJson(json["crs"]),
        type: json["type"],
    );

    Map<String, dynamic> toJson() => {
        "coordinates": List<dynamic>.from(coordinates.map((x) => List<dynamic>.from(x.map((x) => List<dynamic>.from(x.map((x) => x)))))),
        "crs": crs.toJson(),
        "type": type,
    };
}

class Crs {
    Crs({
        this.properties,
        this.type,
    });

    Properties properties;
    String type;

    factory Crs.fromJson(Map<String, dynamic> json) => Crs(
        properties: Properties.fromJson(json["properties"]),
        type: json["type"],
    );

    Map<String, dynamic> toJson() => {
        "properties": properties.toJson(),
        "type": type,
    };
}

class Properties {
    Properties({
        this.name,
    });

    String name;

    factory Properties.fromJson(Map<String, dynamic> json) => Properties(
        name: json["name"],
    );

    Map<String, dynamic> toJson() => {
        "name": name,
    };
}

Upvotes: 1

Related Questions