~ihabunek/triglav

ref: 7bdb88d4d88886e08c456f7ee012d7a343a73731 triglav/lib/triglav/geo_json.ex -rw-r--r-- 1.4 KiB
7bdb88d4Ivan Habunek Split validation from persisting errors 5 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
defmodule Triglav.GeoJSON do
  alias Triglav.Schemas.Osmosis.{Way, Node}

  def to_feature(object, properties \\ %{})

  def to_feature(%Way{} = way, properties) do
    properties = Map.merge(%{id: way.id, type: "W"}, properties)
    feature(geometry(way), properties)
  end

  def to_feature(%Node{} = node, properties) do
    properties = Map.merge(%{id: node.id, type: "N"}, properties)

    feature(geometry(node), properties)
  end

  defp geometry(%Node{} = node) do
    %{
      type: "Point",
      coordinates: Tuple.to_list(node.geom.coordinates)
    }
  end

  defp geometry(%Way{} = way) do
    %{
      type: "LineString",
      coordinates: Enum.map(way.linestring.coordinates, &Tuple.to_list/1)
    }
  end

  def feature(geometry, properties \\ %{}) do
    %{
      type: "Feature",
      properties: properties,
      geometry: geometry
    }
  end

  def feature_collection(features) do
    %{
      type: "FeatureCollection",
      features: features
    }
  end

  @spec nodes_to_linestring([Node.t()]) :: map()
  def nodes_to_linestring(nodes) do
    coordinates = Enum.map(nodes, &Tuple.to_list(&1.geom.coordinates))

    %{
      type: "LineString",
      coordinates: coordinates
    }
  end

  @spec ways_to_multilinestring([Way.t()]) :: map()
  def ways_to_multilinestring(ways) do
    %Geo.MultiLineString{
      coordinates: Enum.map(ways, & &1.linestring.coordinates)
    }
  end
end