首页
/ Gmaps4rails 技术文档

Gmaps4rails 技术文档

2024-12-24 07:06:03作者:凤尚柏Louis

1. 安装指南

首先,确保您的项目Gemfile文件中包含了gmaps4rails gem:

gem 'gmaps4rails'

然后执行以下命令安装gem:

bundle install

2. 项目使用说明

在HTML文件中添加一个div元素,用于承载地图:

<div style='width: 800px;'>
  <div id="map" style='width: 800px; height: 400px;'></div>
</div>

接着,在您的DOM中插入Google地图的JavaScript库和其他必要的脚本:

<script src="//maps.google.com/maps/api/js?key=[你的API密钥]"></script>
<script src="//cdn.rawgit.com/mahnunchik/markerclustererplus/master/dist/markerclusterer.min.js"></script>
<script src='//cdn.rawgit.com/printercu/google-maps-utility-library-v3-read-only/master/infobox/src/infobox_packed.js' type='text/javascript'></script> <!-- 如果需要自定义信息框 -->

还需要引入underscore.js,可以通过以下链接找到:http://underscorejs.org/ (lo-dash也可兼容)。

如果您的项目使用资产管道(asset pipeline),添加以下代码到您的JavaScript文件:

//= require underscore
//= require gmaps/google

如果没有资产管道,您需要复制JavaScript或CoffeeScript文件:

rails g gmaps4rails:copy_js
rails g gmaps4rails:copy_coffee

然后,在JavaScript中创建地图:

handler = Gmaps.build('Google');
handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){
  markers = handler.addMarkers([
    {
      "lat": 0,
      "lng": 0,
      "picture": {
        "url": "http://people.mozilla.com/~faaborg/files/shiretoko/firefoxIcon/firefox-32.png",
        "width":  32,
        "height": 32
      },
      "infowindow": "hello!"
    }
  ]);
  handler.bounds.extendWith(markers);
  handler.fitMapToBounds();
});

3. 项目API使用文档

以下是如何在控制器中生成JSON的示例:

@users = User.all
@hash = Gmaps4rails.build_markers(@users) do |user, marker|
  marker.lat user.latitude
  marker.lng user.longitude
end

在视图中使用该JSON:

<script>
    markers = handler.addMarkers(<%= raw @hash.to_json %>);
</script>

4. 项目安装方式

请按照上述“安装指南”中的步骤操作,确保所有的依赖都已经正确安装并配置。

以上是Gmaps4rails项目的基本技术文档,更多自定义选项和详细配置,请参考项目wiki。

登录后查看全文
热门项目推荐
相关项目推荐