寻找获得" lat"的最佳方法。和" lon"出于这个:
{:ok,
%Geocoder.Coords{
bounds: %Geocoder.Bounds{
bottom: 43.1949619,
left: -86.2468396,
right: -86.24483359999999,
top: 43.19497399999999
},
lat: 43.19497399999999,
location: %Geocoder.Location{
city: "Muskegon Heights",
country: "United States",
country_code: "US",
formatted_address: "Amsterdam, Muskegon Heights, MI 49444, USA",
postal_code: "49444",
state: "Michigan",
street: "Amsterdam",
street_number: nil
},
lon: -86.24586719999999
}}
感谢您的建议。
答案 0 :(得分:4)
你可以使用这样的模式匹配:
# assuming the value in your question is stored in `value`
{:ok, %{lat: lat, lon: lon}} = value
IO.inspect lat
IO.inspect lon
您还可以使用点来提取整个值并访问lat
和lon
:
{:ok, coords} = value
IO.inspect coords.lat
IO.inspect coords.lon
答案 1 :(得分:1)
再次为了完整起见,似乎你也可以在这里使用Map.get / 3。
defmodule Geocoder.Bounds do
defstruct [:bottom, :left, :right, :top]
end
defmodule Geocoder.Location do
defstruct [
:city,
:country,
:country_code,
:formatted_address,
:postal_code,
:state,
:street,
:street_number
]
end
defmodule Geocoder.Coords do
defstruct [:bounds, :lat, :location, :lon]
end
defmodule Test do
alias Geocoder.{Bounds, Location, Coords}
def new() do
b = %Bounds{bottom: 43.19, left: -86, right: -86, top: 43}
l = %Location{
city: "abc",
country: "usa",
country_code: "usa",
formatted_address: "",
postal_code: "49444",
state: "Michigan",
street: "Amsterdam",
street_number: nil
}
{:ok, %Coords{bounds: b, lat: 43.1, location: l, lon: -86.2}}
end
def get_lat() do
g = new()
elem(g, 1) |> Map.get(:lat)
end
def get_lon() do
g = new()
elem(g, 1) |> Map.get(:lon)
end
end
虽然我认为@ dogbert的方法更好,但我再次提供这个只是为了提供一个潜在的选择。
BTW,我知道我没有使用与示例代码相同的所有值,但我厌倦了复制/粘贴示例中的代码。无论如何,其中的差异不应该是显着的。