Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add place_to to location result #31

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

tab
Copy link

@tab tab commented Jul 14, 2023

Added the place_id attribute to the Location class

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

@ab320012
Copy link

ab320012 commented Oct 2, 2023

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
Copy link
Author

tab commented Oct 4, 2023

@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