Skip to content

Add place_to to location result - #31

Open
tab wants to merge 1 commit into
zilverline:masterfrom
tab:feature/add-place_id-to-location
Open

Add place_to to location result#31
tab wants to merge 1 commit into
zilverline:masterfrom
tab:feature/add-place_id-to-location

Conversation

@tab

@tab tab commented Jul 14, 2023

Copy link
Copy Markdown

Added the place_id attribute to the Location class

location = Google::Maps.geocode('Science Park 400, Amsterdam').first
location.place_id
=> "ChIJIcrTFogJxkcRb0dbtBG4pQc"

@ab320012

ab320012 commented Oct 2, 2023

Copy link
Copy Markdown

I need this change as well

@tab
tab force-pushed the feature/add-place_id-to-location branch from f1849f8 to 27a547a Compare October 4, 2023 11:53
@tab

tab commented Oct 4, 2023

Copy link
Copy Markdown
Author

@ab320012 while this PR is not yet merged I used a monkey-patch

# frozen_string_literal: true

Google::Maps.configure do |config|
  config.authentication_mode = Google::Maps::Configuration::API_KEY
  config.api_key = ENV.fetch('GOOGLE_GEOCODING_API_KEY')
end

# NOTE: Location class monkey-patch
module Google
  module Maps
    class Location
      attr_reader :address, :latitude, :longitude, :place_id, :components
      alias to_s address

      def initialize(address, latitude, longitude, place_id, components = {})
        @address = address
        @latitude = latitude
        @longitude = longitude
        @place_id = place_id
        @components = components
      end

      def lat_lng
        [latitude, longitude]
      end

      def self.find(address, language = :en)
        args = { language:, address: }

        API.query(:geocode_service, args).results.map do |result|
          Location.new(
            result.formatted_address,
            result.geometry.location.lat,
            result.geometry.location.lng,
            result.place_id,
            format_components(result.address_components)
          )
        end
      end

      def self.format_components(address_components)
        address_components.each_with_object({}) do |v, acc|
          types = v['types']
          types.each do |t|
            acc[t] ||= []
            acc[t] << v['long_name']
            acc[t] << v['short_name'] if v['short_name'] != v['long_name']
          end
        end
      end
    end
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants