2011-11-25 63 views
4

在我的Rails应用程序中,我有一个帮助程序方法location可获取给定IP地址的坐标,并使其在所有控制器和视图中都可用。例如location.latitude返回用户的纬度。你明白了。从JavaScript和Rails传递参数

我也有一些Javascript,它基于给定的经纬度对从Google Maps API绘制地图。问题是我不知道如何将参数传递给JavaScript!

中的JavaScript驻留在“application.js中”,看起来像这样:

$(document).ready(function() 
    { 

    //Map options...I want the params to go into the var 'MapOptions' below 

    function initialize() { 
     var mapOptions = { 
     center: new google.maps.LatLng(40.764698,-73.978972), 
     zoom: 13, 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
     }; 

    //Setup and Draw the Map... 
    //.................................... 
    }; 

地图本身被称为像这样的HTML。没有一个明显的方法来通过params。

<div id="map_canvas"> 
    <!-- The Map gets drawn here! --> 
</div> 

我知道这可能是一个明显的问题,但我从来没有过这样的感觉从我的应用程序传递参数为JavaScript。

回答

6

我认为data attributes在这里工作得很好。

HTML

<div id="map_canvas" data-latitude="40.764698" data-longitude="-73.978972"> 
    <!-- The Map gets drawn here! --> 
</div> 

或与您的助手

<div id="map_canvas" data-latitude="<%= location.latitude %>" data-longitude="<%= location.longitude %>"> 
    <!-- The Map gets drawn here! --> 
</div> 

JS

$(document).ready(function() { 

    //Map options...I want the params to go into the var 'MapOptions' below 

    function initialize() { 
    var mapDiv = $('#map_canvas'); 
    var lat = mapDiv.data('latitude'), 
     lng = mapDiv.data('longitude'); 

    var mapOptions = { 
     center: new google.maps.LatLng(lat,lng), 
     zoom: 13, 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
    }; 

    //Setup and Draw the Map... 
    //.................................... 
}; 
+0

嘿乔!迎接你的另一个晚上! JavaScript可能是我最薄弱的一点,因为我只是在必要时才开始做前端。再次感谢人! – thoughtpunch

+1

对于一个写得好的答案和你的姓氏+1。 ;) – ahsteele

2

您可以将lat和long分配给视图中的隐藏字段。并在您的applicatons.js脚本只是让他们像$("#lat").val()不是最终的解决方案,但应该运作良好。

1

将数据传递到JavaScript可以与刚创业板
例如的帮助下被简化,定义任何与去Ñ在控制器中:

class FooController < ApplicationController 

    def show_map 
    #.... 
    gon.mapLatLong = [40.764698,-73.978972] 

接着,输出该ERB标签在视图

<%= include_gon %> 

坤在于控制器定义值将改变成在视图中的JavaScript变量。 因此,你可以在你的JavaScript写这样

center: new google.maps.LatLng(gon.mapLatLong[0],gon.mapLatLong[1]), 

参考:
https://github.com/gazay/gon
http://railscasts.com/episodes/324-passing-data-to-javascript

+0

不应该是:'center:new google.maps.LatLng(gon.mapLatLong [0],gon.mapLatLong [1]),' – Santosh

+0

谢谢@Santosh我更正了它 –