Quantcast
Channel: Ruby – Live. Interesting. Stories
Viewing all articles
Browse latest Browse all 10

Custom Google Maps Marker With YM4R_GM

$
0
0

In one my Rails applications, I allow the user to search for surrounding businesses from their current location. I always showed them a You Are Here marker. The issue I had with this was that the marker was always the icon as the search results. Differentiating these markers is actually extremely easy with ym4r_gm plugin.

First thing is to find a custom icon that you want to use. You can just Google for custom Google maps icons. I chose to use their default icon, just in a different blue. (You can download it here so you are working with what I am working with for this example). The next thing I did was to use the Google custom markers web site to find the proper config options for the icon.

The Rails code is just used to create Javascript. That is why it’s a good idea to run the image through custom markers website to get the Javascript output. Ym4r_gm just turns the Ruby options specified into Javascript. There are more options available, but this is the bare minimum necessary to create a separate icon. All you need to do is use the option names given to you by the custom markers site and “Rubyify” them in GIcon.new (note: this is slightly harder than it sounds).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@map.icon_global_init(
  GIcon.new(  :image => "/images/gmap_blue_icon.png",
              :icon_size => GSize.new(32, 32),
              :icon_anchor => GPoint.new(16, 32),
              :info_window_anchor => GPoint.new(16, 0)), 'youarehere_icon')
youarehere_icon = Variable.new('youarehere_icon')
@map.center_zoom_init( [ @location.lat, @location.lng ], 15 )
youarehere = GMarker.new( [ @location.lat, @location.lng ],
  :title => "You Are Here",
  :info_window => "You Are Here",
  :icon => youarehere_icon,
  :draggable => false
)

@map.declare_init( youarehere, 'youarehere' )
@map.overlay_init( youarehere )

A few things worth nothing about this code in order to better understand what it’s doing.

If you don’t have the icon_size set properly, then your icon will look funny when the map renders. The icon_anchor and info_window_anchor are just coincidentally half of 32, this is not always the case. And that last item in GIcon.new is what is going to be the Javascript variable name. For sanity’s sake, I chose to keep the Ruby variable name and Javascript variable names consistent. The Variable.new line creates a ym4r_gm icon object in Ruby to be passed to the :icon parameter of the youarehere marker.

The rest of the code is similar to your regular ym4r_gm map icon stuff.

The post Custom Google Maps Marker With YM4R_GM appeared first on Live. Interesting. Stories.


Viewing all articles
Browse latest Browse all 10

Trending Articles