---
title: "Rails 當中使用 Google Map：YM4R"
author: "thegiive"
date: "2007-03-11T09:22:17Z"
tags: ["Google", "JavaScript", "Rails", "Ruby", "SVN"]
slug: "rails-google-map-ym4r"
draft: false
lastmod: "2007-03-11T09:22:17Z"
id: 59160
url: "https://thegiive.iteye.com/blog/59160"
---

[![](http://bp0.blogger.com/_8vS0KjIsbko/RfPA8MITC3I/AAAAAAAAAGQ/sUaOmcMMyq0/s400/%E6%93%B7%E5%9C%96_1.png)](http://bp0.blogger.com/_8vS0KjIsbko/RfPA8MITC3I/AAAAAAAAAGQ/sUaOmcMMyq0/s1600-h/%E6%93%B7%E5%9C%96_1.png)  
最近發現 Google Map 很好玩，想要玩玩 Ruby on Rails 上面的 Google Map，就找上了 [YM4R 這個](http://thepochisuperstarmegashow.com/projects/#ym4r) [Rails Plugin](http://thepochisuperstarmegashow.com/projects/#ym4r)，發現 YM4R 使用 Google Map真是方便呀，彈指之間搞定。YM4R 這個 Plugin 就是讓Ruby on Rails 上面使用 Yahoo Map 跟 Google Map 的 Rails Plugin。以下介紹一下這個 YM4R 怎麼使用。

安裝：

ruby script/plugin install svn://rubyforge.org/var/svn/ym4r/Plugins/GM/trunk/ym4r\_gm

這個動作會把相關的 file copy 到 config，vendor/plugins, public/javascripts 裡面去，如此就把這個 YM4Rplugin 裝完了。

使用：  
要使用這個 plugin 一共分成 controller 跟 view 兩個部份。

Controller：

在 controller 裡面加入底下的 code ，底下的 code 是改自[這個網頁](http://www.juixe.com/techknow/index.php/2007/02/07/rails-google-maps-plugin/)，他會 initial 一個 Gmap Object，顯示我們指定的位址。我們這裡舉台北為例子，台北的經緯度根據 [Wikipedia](http://zh.wikipedia.org/wiki/%C3%A5%C2%8F%C2%B0%C3%A5%C2%8C%C2%97%C3%A5%C2%B8%C2%82) ，為東經121.6度，北緯24.9度，放大的程度為 7，並且有一個 info\_windows。

> ```
> latitude = '24.9'
longitude = '121.6'
@map = GMap.new("map_div_id")
@map.control_init(:large_map => true, :map_type => true)
@map.center_zoom_init([latitude,longitude], 7)

marker = GMarker.new([latitude, longitude],
                  :title => "台北", :info_window => "我在台北呦～")
@map.overlay_init(marker)
> ```

View ：

Google Map 使用方式都是 Javascript。要在 Ruby on Rails View 裡面使用方式，分成兩個步驟，第一個是在 head 裡面加入相關的 Javascript

> &lt;%= GMap.header %&gt;

第二個就是在 Body 裡面，顯示剛剛在 controller 裡面設定完成的 @map 變數，這裡寬跟高都設定 600

> &lt;%= @map.to\_html %&gt;  
> &lt;%= @map.div(:width =&gt; 600, :height =&gt; 600) %&gt;

啟動：

請打入 http://localhost:3000/controller\_name/ 就可以看到台北的 Google Map 了

等等，我都沒看到 Google API Key ？

是的，我們上面的例子都不用設定 Google API Key 的原因，是因為我們使用的 Domain 是 http://localhost:3000/ ，而這個 Plugin 已經預設裝入 http://localhost:3000/ 的 Google API Key 。

如果你想設定你的 Domain ，請到 config/gmaps\_api\_key.yml 裡面設定，請將你[申請的 Google API Key](http://www.google.com/apis/maps/signup.html) ，放入 production 設定底下。話說，我不知道為啥我明明跑的是 development mode，但是將申請好的 API Key 放在 development 底下他不 work，反正似乎只能放在 production mode 才可以 work。

延伸閱讀：

1. [Rails Google Maps Plugin 教學](http://www.juixe.com/techknow/index.php/2007/02/07/rails-google-maps-plugin/)
2. [YM4R Project Hompage](http://thepochisuperstarmegashow.com/projects/#ym4r)