Giter Site home page Giter Site logo

codablegeojson's Introduction

CodableGeoJSON

CocoaPods Compatible SPM compatible

This implementation of GeoJSON conforms to rfc7946 and is designed for usage with Codable objects.

This library includes both a dynamic and static variant of the GeoJSON models. The static variant is useful when handling pre-defined GeoJSON responses.

Requirements

  • iOS 12.0+ / macOS 10.13+ / tvOS 12.0+ / watchOS 4.0+
  • Xcode 15+
  • Swift 5.8+

Usage

Static Models

The static models are recommended for when your project is set up to load data for which you know what structure to expect.

For example, if you know that you're loading a list of locations inside a "FeatureCollection" like this:

{
  "features": [
    {
      "geometry": {
        "coordinates": [
          -0.452207,
          51.471403
        ],
        "type": "Point"
      },
      "properties": {
        "address": "Longford, Hounslow TW6 1DB, UK",
        "name": "Heathrow Airport"
      },
      "type": "Feature"
    }
  ],
  "type": "FeatureCollection"
}

You can define the model using a struct and a typealias.

struct LocationProperties: Codable {
    let address: String
    let name: String
}

typealias LocationFeatureCollection = GeoJSONFeatureCollection<PointGeometry, LocationProperties>

The benefit here is that you can access the specific geometry and all the properties directly, without having to perform any introspection. E.g.

let locationFeatures = try JSONDecoder().decode(LocationFeatureCollection.self, from: data)
let firstFeature = locationFeatures.features.first
firstFeature?.geometry.longitude // -0.452207
firstFeature?.properties?.name // "Heathrow Airport"

Geometry Collection

A geometry collection is, by definition, not statically typed, as it can contain a mixed array of different GeoJSON geometry types. Therefore you will need to check each array by hand. (If somebody has a way of simplifying this, feel free to post a PR ๐Ÿ˜‰)

let geometryColection = try JSONDecoder().decode(GeometryCollection.self, from: data)
if geometryColection.geometries.count > 0,
    case GeoJSON.Geometry.point(let pointCoordinates) = geometryColection.geometries[0] {
    let point = PointGeometry(coordinates: pointCoordinates)
} else {
    // Failed to get expected geometry
}

Empty properties

If you don't want or need any of the properties of the feature, you can define an empty struct and set it as the Properties template parameter.

struct EmptyProperties: Codable {}

typealias PointFeature = GeoJSONFeature<PointGeometry, EmptyProperties>

This will result in the "Feature" objects containing only a point coordinate.

Dynamic Models

The dynamic models should only be used when the expected structure is undefined or may change.

First, let's assume that you have a GeoJSON data object. The first step is to decode it.

do {
    switch try JSONDecoder().decode(GeoJSON.self, from: data) {
    case .feature(let feature, _):
        handleGeometry(feature.geometry)
    case .featureCollection(let featureCollection, _):
        for feature in featureCollection.features {
            handleGeometry(feature.geometry)
        }
    case .geometry(let geometry, _):
        handleGeometry(geometry)
    }
} catch {
    // Handle decoding error
}

Then you can explore the different geometries provided.

func handleGeometry(_ geometry: GeoJSONGeometry?) {
    guard let geometry = geometry else { return }

    switch geometry {
    case .point(let coordinates):
        break
    case .multiPoint(let coordinates):
        break
    case .lineString(let coordinates):
        break
    case .multiLineString(let coordinates):
        break
    case .polygon(let coordinates):
        break
    case .multiPolygon(let coordinates):
        break
    case .geometryCollection(let geometries):
        for geometry in geometries {
            handleGeometry(geometry)
        }
    }
}

If you know the geometry type that you're looking for, you can try and get it directly.

func handleGeometry(_ geometry: GeoJSONGeometry?) {
    guard case GeoJSONGeometry.polygon(let coordinates)? = geometry else { return }

    displayPolygon(linearRings: coordinates)
}

Installation

CocoaPods

To integrate CodableGeoJSON into your Xcode project using CocoaPods, specify it in your Podfile:

pod 'CodableGeoJSON'
Swift Package Manager

You can use The Swift Package Manager to install CodableGeoJSON by adding the proper description to your Package.swift file:

import PackageDescription

let package = Package(
    name: "YOUR_PROJECT_NAME",
    targets: [],
    dependencies: [
        .package(url: "https://github.com/guykogus/CodableGeoJSON.git", from: "1.2.0")
    ]
)

Next, add CodableGeoJSON to your targets dependencies like so:

.target(
    name: "YOUR_TARGET_NAME",
    dependencies: [
        "CodableGeoJSON",
    ]
),

Then run swift package update.

License

CodableGeoJSON is available under the MIT license. See the LICENSE file for more info.

codablegeojson's People

Contributors

guykogus avatar via-guy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

codablegeojson's Issues

Protocol 'GeoJSONGeometry' can only be used as a generic constraint

I'm a bit of noob so forgive me if the issue is obvious. I'm trying to use the func below from the readme

func handleGeometry(_ geometry: GeoJSONGeometry?) {
    guard let geometry = geometry else { return }

    switch geometry {
    case .point(let coordinates):
        break
    case .multiPoint(let coordinates):
        break
    case .lineString(let coordinates):
        break
    case .multiLineString(let coordinates):
        break
    case .polygon(let coordinates):
        break
    case .multiPolygon(let coordinates):
        break
    case .geometryCollection(let geometries):
        for geometry in geometries {
            handleGeometry(geometry)
        }
    }
}

but I get the error in the generic constraint error shown in the Title. So, I modified it to this:

 func handleGeometry<T: GeoJSONGeometry>(_ geometry: T?) {
        guard let geometry = geometry else { return }
        
        switch geometry {

which solves the problem (I think) but each switch case has an error

Pattern cannot match values of type 'T'

I'm not sure how to resolve this. Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.