jeroenbourgois

jeroenbourgois

I am saving a model that has a latitude and a longitude. Alongside I would like to save a POINT into my database from those two values. But I cannot find a way to use the POINT type in Ecto. I believe I will need to make a custom Ecto Type, but I am far too inexperienced to do it, and the online tutorials I find seem to tackle simpler field types.

Does anyone have any experience with Geo, Ecto and MySQL? I saw that Mariaex actually supports the Geo types, but I am clueless how to use it with Ecto.

Thanks!

Showing Posts 1 to 4

kokolegorille

kokolegorille

You might find some information about PostGis Ecto integration in this github project.

https://github.com/bryanjos/geo_postgis

It is for postgres, but might be helpful nevertheless.

jeroenbourgois

jeroenbourgois OP

We just got it working here! It might have been obvious but we are really new to all of this. So, turns out, mariaex already had support for Geometry. But to get it to work with Ecto, we needed to define a custom type.

defmodule MyApp.EctoPoint do
  @behaviour Ecto.Type
  def type, do: Mariaex.Geometry.Point

  # Casting from input into point struct
  def cast(value = %Mariaex.Geometry.Point{}), do: {:ok, value}
  def cast(_), do: :error

  # loading data from the database
  def load(data) do
    {:ok, data}
  end

  # dumping data to the database
  def dump(value = %Mariaex.Geometry.Point{}), do: {:ok, value}
  def dump(_), do: :error
end

Then, in your schema you can use that type. And in our case, we were always creating the point from user input that went into lat/long input fields, so in the changeset we cast those two to a proper Point.

defmodule MyApp.Restaurant do
  use Ecto.Schema

  import Ecto
  import Ecto.Changeset

  schema "pois" do
    # ... fields
    field(:lat, :float)
    field(:long, :float)
    field(:point, MyApp.EctoPoint) # <-- custom type here

    timestamps()
  end

  def changeset(%MyApp.Restaurant{} = restaurant, attrs \\ %{}) do
    poi
    |> cast(attrs, [:lat, :long])
    |> validate_required([:name])
    |> cast_geo()
  end

  def cast_geo(%Ecto.Changeset{changes: %{lat: lat, long: long}} = changeset) do
    point = %Mariaex.Geometry.Point{coordinates: {lat, long}}
    put_change(changeset, :geometry, point)
  end

  def cast_geo(changeset), do: changeset
end

Works like a charm! Only need to check what type to use in the migration.

jeroenbourgois

jeroenbourgois OP

Just as a follow-up, we do understand the custom Ecto.Type a bit better. We still need the seperate cast like above because the actual Point was not submitted with the form, but for another component we did post the string variant of a Polygon. There inside the cast/1 function we constructed the correct Mariaex.Geometry.Polygon type, so we could just put that field the cast method of our changeset and everything worked!

defmodule MyApp.Ecto.Polygon do
  @behaviour Ecto.Type
  def type, do: Mariaex.Geometry.Polygon

  # Casting from input into point struct
  # The point string is in the form of "lat long, lat long, lat long"
  def cast(points_string) when is_binary(points_string) do
    coordinates =
      points_string
      |> String.split(",")
      |> Enum.map(fn raw_coord ->
        [lat, long] = raw_coord |> String.trim() |> String.split(" ")
        to_coord(lat, long)
      end)

    polygon = %Mariaex.Geometry.Polygon{
      coordinates: [coordinates]
    }

    {:ok, polygon}
  end

  def cast(_), do: :error

  # loading data from the database
  def load(data) do
    {:ok, data}
  end

  # dumping data to the database
  def dump(value = %Mariaex.Geometry.Polygon{}), do: {:ok, value}
  def dump(_), do: :error

  defp to_coord(lat_s, long_s), do: {String.to_float(lat_s), String.to_float(long_s)}
end
— All posts loaded —

Where Next? Top

Trending in Questions Top

katta
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
achenet
Hello, I’m trying to build a basic Phoenix web-app, and I’d like to use Tailwind. However, when I launch mix phx.server, I get an error...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
Cxx-mlr
I’m working on a small exercise involving update_in/3, and I came up with this solution: data = %{ name: "Periodic Table", category:...
New
ChrisAmelia
I’ve got trouble wrapping my head around the order in which functions are called in this snippet (from Phoenix’s authentication): toke...
New
dillonoconnor
Is there any way to avoid the Hologram compiler running when using iex? It seems like the front-end code could potentially be disregarded...
New
thiagogsr
** (ArgumentError) expected :max_attempts to be a positive integer, got: {:@, [line: 10, column: 19], [{:max_attempts, [line: 10, column:...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New
KristerV
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews