mapselixir

How to get values out of a nested map


Looking for best way to get the values of "lat" and "lon" out of this:

{: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
}}

Thanks for advice.


Solution

  • Again for sake of completeness, it seems as if you could use Map.get/3 here too.

    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
    

    Although I think @dogbert's approach is better, I offer this again just to offer a potential alternative.

    BTW, I know I didn't use all the same values as your sample code but I was getting tired of copy/pasting the code from your example. And the differences in that shouldn't be salient anyway.