2011-11-25 62 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我更正了它 –