Elixir 如何一步将数组和散列匹配,并将其放置在模型实例方法中?
如何转换Elixir 如何一步将数组和散列匹配,并将其放置在模型实例方法中?,elixir,phoenix-framework,Elixir,Phoenix Framework,如何转换Geo.Point坐标属性包含%Geo.Point{coordinates:{49.44,17.87},srid:nil}后Geo.JSON.encode:%{“coordinates”=>[49.44,17.87],“type”=>“Point” 根据以下公式: %{latitude: latitude, longitude: longitude} 这是我目前的方法,如何一步到位 %{"coordinates" => [latitude,longitude] } = Geo.J
Geo.Point
坐标属性包含%Geo.Point{coordinates:{49.44,17.87},srid:nil}
后Geo.JSON.encode
:%{“coordinates”=>[49.44,17.87],“type”=>“Point”
根据以下公式:
%{latitude: latitude, longitude: longitude}
这是我目前的方法,如何一步到位
%{"coordinates" => [latitude,longitude] } = Geo.JSON.encode(place.coordinates)
coordinates = %{latitude: latitude, longitude: longitude}
如何将其放置在实例方法中,以便调用后返回新公式,例如place.to\u lat\u lng
defmodule MyApp.Place do
use MyApp.Web, :model
schema "place" do
field :coordinates, Geo.Point
timestamps
end
def to_lat_lng do
#...format coordinates
end
end
您不需要进行JSON编码。可以将Geo.Point作为参数传递给函数。我会这样做:
def to_lat_lng(%Geo.Point{coordinates: {lat, long}}) do
%{latitude: lat, longitude: long}
end
请注意,这不是一个实例方法。它只是一个函数。您应该知道一些其他术语,因为它可能会帮助您编写文档:在elixir中,我们有一个列表,而不是数组。我们也使用地图或字典