Problem with encoding Geo.Point

Hello, I have a record structure that contains Geo.Point coordinates field(geo_postgis).
Thats I receive from db when I’m using serializer.

    coordinates: %Geo.Point{
      coordinates: {48.51572187715065, 48.51572187715065},
      properties: %{},
      srid: 4326
    id: 10,
    name: "default name"

When I’m try to send them to my client through websocket, I got error that says

** (Poison.EncodeError) unable to encode value: {48.442894571035936, 48.442894571035936}

My serializer

defmodule ScenesSerializer do

  use Remodel

  attributes [:name, :id, :coordinates]

Seems quite right.

Poison (or any other Json encoder for that matter) doesn’t support tuples, because they don’t exists in Json.

One way to solve the problem is to convert the tuple to a list

{48.51572187715065, 48.51572187715065} |> Tuple.to_list() |> Poison.encode
{:ok, "[48.51572187715065,48.51572187715065]"}

In your specific case, Geo supports encoding Points to a Json compatible format.
You have to use Geo.JSON.encode(point)

From their Github page

#Examples using Poison as the JSON parser

iex(1)> Geo.JSON.encode(point)
{:ok, %{ "type" => "Point", "coordinates" => [100.0, 0.0] }}

iex(2)> point = Poison.decode!("{ \"type\": \"Point\", \"coordinates\": [100.0, 0.0] }") |> Geo.JSON.decode
%Geo.Point{ coordinates: {100.0, 0.0}, srid: nil }

iex(3)> Geo.JSON.encode!(point) |> Poison.encode!
1 Like