rails_google_map 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 3c730ca865297fdd78afc25746eccf4de2b97b89b61ccf664387675da6239092
4
+ data.tar.gz: bfae7aa4b5883c2599ff1850b6b7a77369b7e38e0bd22927070edce3bd9c96f5
5
+ SHA512:
6
+ metadata.gz: 2f36c8ece99a43f71e0797bb46310341dc0e4c715bee3b94d95e691d74d6b31b8f6fe7e4f4c7c0acece0ab694eaa5d091a0797c0c884dbbca19fd03190861eae
7
+ data.tar.gz: 7e7c3d47db516653be733426afe6177e0cac2299f644b2bcf6f680f676d604247f99767a2979327ed6672f4a3893a112fa06750897d86a569c32de9a3394e514
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/CHANGELOG.md ADDED
@@ -0,0 +1,19 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2026-08-25
4
+
5
+ - Initial release.
6
+ - `google_map_for` view helper renders an embedded Google Map from an address
7
+ or a lat/lng pair.
8
+ - `google_map_embed_url` returns the embed URL on its own, for callers that
9
+ want to build their own markup.
10
+ - `embed_google_map` offers the same thing with a plain options hash.
11
+ - Falls back to Google's keyless embed endpoint when no API key is configured,
12
+ so a map renders without a key or a billing account.
13
+ - `RailsGoogleMap::Geocoder.coordinates_for` turns an address into coordinates
14
+ via the Google Geocoding API.
15
+ - Rails engine mixes the helpers into ActionView automatically.
16
+ - Supports Ruby >= 2.5.1 and Rails (ActionView) 5.0 through 8.x.
17
+ - Requires "logger" before ActionView, so Rails 5 and 6 still load against
18
+ concurrent-ruby 1.3.5+, which dropped the implicit require that
19
+ ActiveSupport < 7.1 relied on.
@@ -0,0 +1,132 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official email address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ shresthabikash2073@gmail.com.
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series of
86
+ actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or permanent
93
+ ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within the
113
+ community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.1, available at
119
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
+
121
+ Community Impact Guidelines were inspired by
122
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
+
124
+ For answers to common questions about this code of conduct, see the FAQ at
125
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126
+ [https://www.contributor-covenant.org/translations][translations].
127
+
128
+ [homepage]: https://www.contributor-covenant.org
129
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
+ [Mozilla CoC]: https://github.com/mozilla/diversity
131
+ [FAQ]: https://www.contributor-covenant.org/faq
132
+ [translations]: https://www.contributor-covenant.org/translations
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Bikash Shrestha
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,222 @@
1
+ # RailsGoogleMap
2
+
3
+ Rails view helpers that drop an embedded Google Map into a page from an address
4
+ or a lat/lng pair.
5
+
6
+ The point of the gem is that it works **with or without a Google Maps API key**.
7
+ With a key it uses the official [Maps Embed API](https://developers.google.com/maps/documentation/embed/get-started)
8
+ and you get zoom, map type and language control. Without one it falls back to
9
+ Google's keyless embed endpoint, which needs no key and no billing account — handy
10
+ for a staging box, a side project, or a page that just needs to show where you are.
11
+
12
+ ```erb
13
+ <%= google_map_for("Thamel, Kathmandu") %>
14
+ ```
15
+
16
+ ## Installation
17
+
18
+ Add it to your Gemfile:
19
+
20
+ ```ruby
21
+ gem "rails_google_map"
22
+ ```
23
+
24
+ Then:
25
+
26
+ ```bash
27
+ bundle install
28
+ ```
29
+
30
+ Or install it directly:
31
+
32
+ ```bash
33
+ gem install rails_google_map
34
+ ```
35
+
36
+ ### Requirements
37
+
38
+ | | Supported |
39
+ | --- | --- |
40
+ | Ruby | 2.5.0 and up (verified on 2.5.1) |
41
+ | Rails (ActionView) | 5.0 through 8.x |
42
+
43
+ The suite is verified against the ends of that range: Ruby 2.5.1 with Rails 5.0
44
+ and 5.2, and Ruby 3.3 with Rails 8.1.
45
+
46
+ **Installing on Ruby 2.5:** use Bundler. The RubyGems that ships with Ruby 2.5
47
+ (2.7.x) ignores a dependency's `required_ruby_version` when resolving, so a bare
48
+ `gem install rails_google_map` reaches for the newest ActionView and fails on a
49
+ Ruby 3.2+ dependency. Bundler resolves it correctly, as does RubyGems 3.0+
50
+ (`gem update --system '~> 3.0'`).
51
+
52
+ ## Configuration
53
+
54
+ Configuration is optional — skip it entirely and the keyless fallback is used.
55
+
56
+ To use the Maps Embed API, create `config/initializers/rails_google_map.rb`:
57
+
58
+ ```ruby
59
+ RailsGoogleMap.configure do |config|
60
+ config.api_key = ENV["GOOGLE_MAPS_EMBED_KEY"]
61
+ config.zoom = 15 # default zoom level
62
+ config.map_type = "roadmap" # "roadmap" or "satellite"
63
+ config.width = "100%" # default iframe width
64
+ config.height = "450" # default iframe height
65
+ config.language = nil # e.g. "en", "ne" — omitted when nil
66
+ end
67
+ ```
68
+
69
+ If you don't set `api_key` at all, the gem picks up `GOOGLE_MAPS_EMBED_KEY` or
70
+ `GOOGLE_MAPS_API_KEY` from the environment, so an initializer is often unnecessary.
71
+
72
+ Keep the key out of source control, and restrict it to the Maps Embed API and to
73
+ your own HTTP referrers in the Google Cloud console — an embed key travels to the
74
+ browser inside the iframe URL and is public by nature.
75
+
76
+ ## Usage
77
+
78
+ In a Rails app the helpers are mixed into every view automatically.
79
+
80
+ ### `google_map_for`
81
+
82
+ ```erb
83
+ <%= google_map_for("Thamel, Kathmandu") %>
84
+
85
+ <%= google_map_for(@business.address, height: "300", zoom: 17) %>
86
+
87
+ <%= google_map_for(lat: 27.7172, lng: 85.3240) %>
88
+
89
+ <%= google_map_for("Thamel", class: "office-map", title: "Our office") %>
90
+ ```
91
+
92
+ The first argument is an address, or a `"lat,lng"` string. Alternatively pass
93
+ `lat:` and `lng:` (`long:` also works). When both an address and coordinates are
94
+ given the **address wins** — lat/lng columns tend to be unreliable, and often a
95
+ whole table shares one default pin.
96
+
97
+ Recognised options:
98
+
99
+ | Option | Default | Notes |
100
+ | --- | --- | --- |
101
+ | `width` | `"100%"` | iframe width |
102
+ | `height` | `"450"` | iframe height |
103
+ | `zoom` | `15` | Embed API only; ignored without a key |
104
+ | `map_type` | `"roadmap"` | Embed API only; `"roadmap"` or `"satellite"` |
105
+ | `language` | `nil` | Embed API only |
106
+ | `api_key` | configured key | override the key for one call |
107
+ | `lat` / `lng` | — | used when no address is given |
108
+
109
+ Any other option is passed straight through as an iframe attribute (`class`,
110
+ `title`, `data`, …).
111
+
112
+ `google_map_for` returns `nil` when there is nothing to show — a blank address, or
113
+ coordinates that are missing or `0,0`. So a caller can guard on it:
114
+
115
+ ```erb
116
+ <% if (map = google_map_for(@business.address, lat: @business.latitude, lng: @business.longitude)) %>
117
+ <div class="google-map"><%= map %></div>
118
+ <% end %>
119
+ ```
120
+
121
+ ### `embed_google_map`
122
+
123
+ The same thing with a plain options hash, if that reads better at the call site:
124
+
125
+ ```erb
126
+ <%= embed_google_map(address: @business.address, height: 300) %>
127
+ <%= embed_google_map(lat: 27.7172, long: 85.3240) %>
128
+ ```
129
+
130
+ ### `google_map_embed_url`
131
+
132
+ Returns just the URL, for when you want to write the markup yourself:
133
+
134
+ ```ruby
135
+ google_map_embed_url("Thamel, Kathmandu")
136
+ # => "https://www.google.com/maps/embed?origin=mfe&pb=!1m2!2m1!1sThamel%2C+Kathmandu"
137
+
138
+ google_map_embed_url("Thamel, Kathmandu", zoom: 18) # with an API key configured
139
+ # => "https://www.google.com/maps/embed/v1/place?key=...&q=Thamel%2C+Kathmandu&zoom=18&maptype=roadmap"
140
+ ```
141
+
142
+ It returns `nil` for a blank query.
143
+
144
+ ### Geocoding
145
+
146
+ If you want to build a richer map with the Maps JavaScript API instead of an
147
+ iframe, the gem can turn an address into coordinates. This one **does** require an
148
+ API key, with the Geocoding API enabled:
149
+
150
+ ```ruby
151
+ RailsGoogleMap::Geocoder.coordinates_for("Thamel, Kathmandu")
152
+ # => { lat: 27.7154, lng: 85.3123 }
153
+ ```
154
+
155
+ Raises `RailsGoogleMap::ConfigurationError` when no key is configured, and
156
+ `RailsGoogleMap::Geocoder::GeocodeError` when the address can't be resolved or the
157
+ API call fails.
158
+
159
+ ### Outside Rails
160
+
161
+ There's no dependency on a booted Rails app — include the helper anywhere:
162
+
163
+ ```ruby
164
+ require "rails_google_map"
165
+
166
+ class MapPresenter
167
+ include RailsGoogleMap::MapHelper
168
+ end
169
+
170
+ MapPresenter.new.google_map_for("Thamel, Kathmandu")
171
+ ```
172
+
173
+ ## Keyless mode: what you give up
174
+
175
+ The keyless endpoint takes the place in `pb`, not in `q` — `/maps/embed?q=` answers
176
+ with a blank page, and `/maps?q=...&output=embed` merely redirects to the `pb` form.
177
+ It is an undocumented endpoint, so treat it as best-effort: it shows the place, but
178
+ `zoom`, `map_type` and `language` are ignored, and Google could change it. Configure
179
+ an API key for anything you depend on.
180
+
181
+ ## Development
182
+
183
+ After checking out the repo, run `bin/setup` to install dependencies. Then run
184
+ `rake spec` to run the tests. You can also run `bin/console` for an interactive
185
+ prompt.
186
+
187
+ To check the gem against a particular Rails release, set `RAILS_VERSION`:
188
+
189
+ ```bash
190
+ RAILS_VERSION=5.0.0 bundle update railties && bundle exec rake spec
191
+ RAILS_VERSION=5.2 bundle update railties && bundle exec rake spec
192
+ bundle update railties && bundle exec rake spec # newest Rails
193
+ ```
194
+
195
+ `Gemfile.lock` is not checked in, precisely so the same Gemfile can resolve under
196
+ Ruby 2.5 and Ruby 3.3.
197
+
198
+ To install this gem onto your local machine, run `bundle exec rake install`. To
199
+ release a new version, update the version number in `version.rb`, then run
200
+ `bundle exec rake release`, which creates a git tag, pushes commits and the tag, and
201
+ pushes the `.gem` file to [rubygems.org](https://rubygems.org).
202
+
203
+ The gemspec builds the file list from `git ls-files`, so **a new file must be
204
+ `git add`ed or it will not be packaged**, even though it works fine locally.
205
+
206
+ ## Contributing
207
+
208
+ Bug reports and pull requests are welcome on GitHub at
209
+ https://github.com/sthaB-kash/rails_google_map. This project is intended to be a
210
+ safe, welcoming space for collaboration, and contributors are expected to adhere to
211
+ the [code of conduct](https://github.com/sthaB-kash/rails_google_map/blob/master/CODE_OF_CONDUCT.md).
212
+
213
+ ## License
214
+
215
+ The gem is available as open source under the terms of the
216
+ [MIT License](https://opensource.org/licenses/MIT).
217
+
218
+ ## Code of Conduct
219
+
220
+ Everyone interacting in the RailsGoogleMap project's codebases, issue trackers, chat
221
+ rooms and mailing lists is expected to follow the
222
+ [code of conduct](https://github.com/sthaB-kash/rails_google_map/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ task default: :spec
@@ -0,0 +1,57 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RailsGoogleMap
4
+ # Raised when the gem is used in a way that needs an API key but none is configured.
5
+ class ConfigurationError < StandardError; end
6
+
7
+ # Holds the gem-wide defaults. Configure it from an initializer:
8
+ #
9
+ # RailsGoogleMap.configure do |config|
10
+ # config.api_key = ENV["GOOGLE_MAPS_EMBED_KEY"]
11
+ # config.zoom = 16
12
+ # end
13
+ #
14
+ # Every setting is optional. Without an +api_key+ the helpers fall back to
15
+ # Google's keyless embed endpoint, which needs no key and no billing account.
16
+ class Configuration
17
+ # Maps Embed API key. Falls back to GOOGLE_MAPS_EMBED_KEY / GOOGLE_MAPS_API_KEY.
18
+ attr_accessor :api_key
19
+ # Default zoom level for the generated map (Embed API only).
20
+ attr_accessor :zoom
21
+ # Default map type: "roadmap" or "satellite" (Embed API only).
22
+ attr_accessor :map_type
23
+ # Default iframe width/height, as passed straight to the iframe attributes.
24
+ attr_accessor :width, :height
25
+ # Language for map labels, e.g. "en" or "ne" (Embed API only).
26
+ attr_accessor :language
27
+
28
+ def initialize
29
+ @api_key = ENV["GOOGLE_MAPS_EMBED_KEY"] || ENV["GOOGLE_MAPS_API_KEY"]
30
+ @zoom = 15
31
+ @map_type = "roadmap"
32
+ @width = "100%"
33
+ @height = "450"
34
+ @language = nil
35
+ end
36
+
37
+ # True when an API key is present, i.e. when the Maps Embed API can be used.
38
+ def api_key?
39
+ !api_key.nil? && !api_key.to_s.strip.empty?
40
+ end
41
+ end
42
+
43
+ class << self
44
+ def configuration
45
+ @configuration ||= Configuration.new
46
+ end
47
+
48
+ def configure
49
+ yield(configuration)
50
+ end
51
+
52
+ # Mostly useful in tests, to get back to a pristine configuration.
53
+ def reset_configuration!
54
+ @configuration = Configuration.new
55
+ end
56
+ end
57
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails/engine"
4
+
5
+ module RailsGoogleMap
6
+ # Makes RailsGoogleMap::MapHelper available in every view of the host app.
7
+ class Engine < ::Rails::Engine
8
+ initializer "rails_google_map.view_helpers" do
9
+ ActiveSupport.on_load(:action_view) do
10
+ include RailsGoogleMap::MapHelper
11
+ end
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "uri"
5
+ require "json"
6
+
7
+ module RailsGoogleMap
8
+ # Converts a free-text address into lat/lng coordinates using the Google
9
+ # Geocoding API. Useful if you want to build a custom map (with markers, info
10
+ # windows, etc.) using the Maps JavaScript API instead of the simple embed
11
+ # iframe. Unlike the view helpers, this always needs an API key.
12
+ class Geocoder
13
+ GEOCODE_URL = "https://maps.googleapis.com/maps/api/geocode/json"
14
+
15
+ class GeocodeError < StandardError; end
16
+
17
+ # Returns { lat: Float, lng: Float } for +address+.
18
+ # Raises ConfigurationError without an API key, GeocodeError on failure.
19
+ def self.coordinates_for(address, api_key: nil)
20
+ key = api_key || RailsGoogleMap.configuration.api_key
21
+ if key.nil? || key.to_s.strip.empty?
22
+ raise ConfigurationError,
23
+ "RailsGoogleMap.configuration.api_key is not set; geocoding requires an API key."
24
+ end
25
+
26
+ raise GeocodeError, "Cannot geocode a blank address." if address.to_s.strip.empty?
27
+
28
+ uri = URI(GEOCODE_URL)
29
+ uri.query = URI.encode_www_form(address: address.to_s, key: key)
30
+
31
+ response = Net::HTTP.get_response(uri)
32
+ unless response.is_a?(Net::HTTPSuccess)
33
+ raise GeocodeError, "HTTP error while geocoding: #{response.code}"
34
+ end
35
+
36
+ data = JSON.parse(response.body)
37
+ unless data["status"] == "OK"
38
+ raise GeocodeError, "Geocoding failed for #{address.inspect}: #{data['status']}"
39
+ end
40
+
41
+ location = data.dig("results", 0, "geometry", "location")
42
+ raise GeocodeError, "Geocoding returned no coordinates for #{address.inspect}." if location.nil?
43
+
44
+ { lat: location["lat"], lng: location["lng"] }
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,111 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "cgi"
4
+ require "uri"
5
+ # ActiveSupport < 7.1 leans on concurrent-ruby having required "logger" for it.
6
+ # concurrent-ruby 1.3.5 dropped that, which makes `require "action_view"` blow up
7
+ # with an uninitialized ActiveSupport::LoggerThreadSafeLevel::Logger on Rails 5
8
+ # and 6. Requiring it up front keeps those versions loadable.
9
+ require "logger"
10
+ require "action_view"
11
+
12
+ module RailsGoogleMap
13
+ # View helpers for embedding a Google Map.
14
+ #
15
+ # In a Rails app the engine mixes this into ActionView automatically, so the
16
+ # helpers are available in every template. Elsewhere, include it yourself.
17
+ module MapHelper
18
+ include ActionView::Helpers::TagHelper
19
+
20
+ # Maps Embed API endpoint. Requires a key and a billing-enabled project.
21
+ EMBED_API_URL = "https://www.google.com/maps/embed/v1/place"
22
+ # Keyless embed endpoint. No key, no billing, but no zoom/maptype either.
23
+ KEYLESS_EMBED_URL = "https://www.google.com/maps/embed"
24
+
25
+ # Renders an <iframe> showing +query+ on a Google Map.
26
+ #
27
+ # <%= google_map_for("Thamel, Kathmandu") %>
28
+ # <%= google_map_for(@business.address, height: "300", zoom: 17) %>
29
+ # <%= google_map_for(lat: 27.7172, lng: 85.3240) %>
30
+ #
31
+ # +query+ may be an address, a "lat,lng" string, or omitted in favour of the
32
+ # :lat/:lng options. Returns nil when there is nothing to show, so a caller
33
+ # can write `if (map = google_map_for(...))`.
34
+ #
35
+ # Any option other than the ones named below is passed straight through as
36
+ # an iframe attribute, e.g. `class: "map"` or `title: "Our office"`.
37
+ def google_map_for(query = nil, width: nil, height: nil, zoom: nil,
38
+ map_type: nil, language: nil, api_key: nil, **html_options)
39
+ query = map_query(query, html_options.delete(:lat), html_options.delete(:lng) || html_options.delete(:long))
40
+ src = google_map_embed_url(query, zoom: zoom, map_type: map_type,
41
+ language: language, api_key: api_key)
42
+ return if src.nil?
43
+
44
+ config = RailsGoogleMap.configuration
45
+ attributes = {
46
+ src: src,
47
+ width: width || config.width,
48
+ height: height || config.height,
49
+ style: "border:0;",
50
+ loading: "lazy",
51
+ referrerpolicy: "no-referrer-when-downgrade",
52
+ allowfullscreen: true,
53
+ frameborder: "0"
54
+ }.merge(html_options)
55
+
56
+ content_tag(:iframe, "", attributes)
57
+ end
58
+
59
+ # The embeddable Google Maps URL for +query+ (an address or a "lat,lng").
60
+ #
61
+ # Uses the official Maps Embed API when a key is configured; without one it
62
+ # falls back to the keyless embed endpoint. That fallback puts the place in
63
+ # `pb`, not `q`: `/maps/embed?q=` answers with a blank page, and
64
+ # `/maps?q=...&output=embed` only redirects to this same URL.
65
+ #
66
+ # Returns nil for a blank query rather than a URL pointing nowhere.
67
+ def google_map_embed_url(query, zoom: nil, map_type: nil, language: nil, api_key: nil)
68
+ query = query.to_s.strip
69
+ return if query.empty?
70
+
71
+ config = RailsGoogleMap.configuration
72
+ key = api_key || (config.api_key if config.api_key?)
73
+ return "#{KEYLESS_EMBED_URL}?origin=mfe&pb=!1m2!2m1!1s#{CGI.escape(query)}" if key.nil? || key.to_s.strip.empty?
74
+
75
+ params = {
76
+ key: key,
77
+ q: query,
78
+ zoom: zoom || config.zoom,
79
+ maptype: map_type || config.map_type,
80
+ language: language || config.language
81
+ }.reject { |_, value| value.nil? || value.to_s.empty? }
82
+
83
+ "#{EMBED_API_URL}?#{URI.encode_www_form(params)}"
84
+ end
85
+
86
+ # Hash-argument flavour of #google_map_for, kept for callers that already
87
+ # build an options hash: :address, :lat and :lng (or :long) plus anything
88
+ # #google_map_for accepts.
89
+ #
90
+ # <%= embed_google_map(address: @business.address, height: 300) %>
91
+ # <%= embed_google_map(lat: 27.7172, long: 85.3240) %>
92
+ #
93
+ def embed_google_map(options = {})
94
+ options = options.to_h.transform_keys(&:to_sym)
95
+ google_map_for(options.delete(:address), **options)
96
+ end
97
+
98
+ private
99
+
100
+ # An address wins over coordinates: lat/lng columns are often unreliable
101
+ # (many rows share one default pin), so they only stand in when no address
102
+ # was given. Treats 0/nil coordinates as "no pin".
103
+ def map_query(address, lat, lng)
104
+ return address.to_s.strip unless address.nil? || address.to_s.strip.empty?
105
+ return if lat.nil? || lng.nil?
106
+ return if lat.to_f.zero? && lng.to_f.zero?
107
+
108
+ "#{lat},#{lng}"
109
+ end
110
+ end
111
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RailsGoogleMap
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "rails_google_map/version"
4
+ require_relative "rails_google_map/configuration"
5
+ require_relative "rails_google_map/map_helper"
6
+ require_relative "rails_google_map/geocoder"
7
+ require_relative "rails_google_map/engine" if defined?(::Rails::Railtie)
8
+
9
+ module RailsGoogleMap
10
+ class Error < StandardError; end
11
+ end
@@ -0,0 +1,43 @@
1
+ module RailsGoogleMap
2
+ VERSION: String
3
+
4
+ class Error < StandardError
5
+ end
6
+
7
+ class ConfigurationError < StandardError
8
+ end
9
+
10
+ class Configuration
11
+ attr_accessor api_key: String?
12
+ attr_accessor zoom: Integer?
13
+ attr_accessor map_type: String?
14
+ attr_accessor width: String | Integer | nil
15
+ attr_accessor height: String | Integer | nil
16
+ attr_accessor language: String?
17
+
18
+ def initialize: () -> void
19
+ def api_key?: () -> bool
20
+ end
21
+
22
+ def self.configuration: () -> Configuration
23
+ def self.configure: () { (Configuration) -> void } -> void
24
+ def self.reset_configuration!: () -> Configuration
25
+
26
+ module MapHelper
27
+ EMBED_API_URL: String
28
+ KEYLESS_EMBED_URL: String
29
+
30
+ def google_map_for: (?untyped query, ?width: untyped, ?height: untyped, ?zoom: Integer?, ?map_type: String?, ?language: String?, ?api_key: String?, **untyped) -> untyped
31
+ def google_map_embed_url: (untyped query, ?zoom: Integer?, ?map_type: String?, ?language: String?, ?api_key: String?) -> String?
32
+ def embed_google_map: (?Hash[untyped, untyped] options) -> untyped
33
+ end
34
+
35
+ class Geocoder
36
+ GEOCODE_URL: String
37
+
38
+ class GeocodeError < StandardError
39
+ end
40
+
41
+ def self.coordinates_for: (untyped address, ?api_key: String?) -> { lat: Float, lng: Float }
42
+ end
43
+ end
metadata ADDED
@@ -0,0 +1,85 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: rails_google_map
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Bikash Shrestha
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2026-08-25 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: actionview
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '5.0'
20
+ - - "<"
21
+ - !ruby/object:Gem::Version
22
+ version: '9'
23
+ type: :runtime
24
+ prerelease: false
25
+ version_requirements: !ruby/object:Gem::Requirement
26
+ requirements:
27
+ - - ">="
28
+ - !ruby/object:Gem::Version
29
+ version: '5.0'
30
+ - - "<"
31
+ - !ruby/object:Gem::Version
32
+ version: '9'
33
+ description: Rails view helpers that render an embedded Google Map from an address
34
+ or lat/lng pair. Uses the Maps Embed API when an API key is configured and falls
35
+ back to Google's keyless embed endpoint when it is not, so a map works without a
36
+ key or a billing account.
37
+ email:
38
+ - shresthabikash2073@gmail.com
39
+ executables: []
40
+ extensions: []
41
+ extra_rdoc_files: []
42
+ files:
43
+ - ".rspec"
44
+ - CHANGELOG.md
45
+ - CODE_OF_CONDUCT.md
46
+ - LICENSE.txt
47
+ - README.md
48
+ - Rakefile
49
+ - lib/rails_google_map.rb
50
+ - lib/rails_google_map/configuration.rb
51
+ - lib/rails_google_map/engine.rb
52
+ - lib/rails_google_map/geocoder.rb
53
+ - lib/rails_google_map/map_helper.rb
54
+ - lib/rails_google_map/version.rb
55
+ - sig/rails_google_map.rbs
56
+ homepage: https://github.com/sthaB-kash/rails_google_map
57
+ licenses:
58
+ - MIT
59
+ metadata:
60
+ homepage_uri: https://github.com/sthaB-kash/rails_google_map
61
+ source_code_uri: https://github.com/sthaB-kash/rails_google_map/tree/v0.1.0
62
+ changelog_uri: https://github.com/sthaB-kash/rails_google_map/blob/master/CHANGELOG.md
63
+ bug_tracker_uri: https://github.com/sthaB-kash/rails_google_map/issues
64
+ documentation_uri: https://github.com/sthaB-kash/rails_google_map#readme
65
+ rubygems_mfa_required: 'true'
66
+ post_install_message:
67
+ rdoc_options: []
68
+ require_paths:
69
+ - lib
70
+ required_ruby_version: !ruby/object:Gem::Requirement
71
+ requirements:
72
+ - - ">="
73
+ - !ruby/object:Gem::Version
74
+ version: 2.5.0
75
+ required_rubygems_version: !ruby/object:Gem::Requirement
76
+ requirements:
77
+ - - ">="
78
+ - !ruby/object:Gem::Version
79
+ version: '0'
80
+ requirements: []
81
+ rubygems_version: 3.5.22
82
+ signing_key:
83
+ specification_version: 4
84
+ summary: Rails view helpers to embed a Google Map.
85
+ test_files: []