2014-06-10 34 views
0

我想在Google地圖中顯示一些座標,它可以很好地從文本文件中獲取,但我不知道如何從數據庫訪問座標。如何在Rails應用程序中使用JavaScript調用數據庫?

下面的代碼用一個文本文件的工作:

<script type="text/javascript"> 

     var map; 
     var markers = []; 

     var mon_fichier = fichier_txt("file.txt"); 
     var elem = mon_fichier.split(','); 
     var tHandleMajActors; // Handle timer majActeurs() 

     function initialize() { 
      var haightAshbury = new google.maps.LatLng(elem[0], elem[1]); 
      var mapOptions = { 
      zoom: 6, 
      center: haightAshbury, 
      mapTypeId: google.maps.MapTypeId.TERRAIN 
      /*mapTypeId: google.maps.MapTypeId.SATELLITE*/ 
      }; 
      map = new google.maps.Map(document.getElementById('map-canvas'), 
       mapOptions); 

      //run realtime view 
      RTrun(); 
     } 

     //RT MENU MANAGEMENT 
     function RTrun(){ 
      movePositionMarker(); 
     } 

     //RT MARKER MANAGEMENT 
     function movePositionMarker(){   //XXX timer 
      var mon_fichier = fichier_txt("file.txt"); 
      var elem = mon_fichier.split(','); 
      i=0;  
      while (i<elem.length) { 
       var myPosition = new google.maps.LatLng(elem[i], elem[i+1]); 
       i=i+2; 
       addMarker(myPosition); 
      } 
      //timer: every 10 s 
      tHandleMajActors = setTimeout(function(){ 
       movePositionMarker(); 
       }, 10000); 
     } 

     // Add a marker to the map and push to the array. 
     function addMarker(location) { 
      var image = 'images/flag.png'; 
      var marker = new google.maps.Marker({ 
      //animation: google.maps.Animation.DROP, 
      position: location, 
      map: map, 
      icon: image 
      }); 
      markers.push(marker); 
     } 

從中我要帶座標被稱爲協調並具有見下表:緯度,:經度,日期,:時間,:tracker_id

謝謝你的幫助!

+0

你是否已經使用jquery了? –

回答

2

不能使用JavaScript直接訪問數據庫,因爲它位於與瀏覽器不同的計算機(服務器)上。你需要在你的應用程序上調用一個動作來返回你想要的數據。

在這種情況下,您希望以json格式獲取數據,所以javascript可以將其直接轉換爲實際的javascript對象。

您可以決定哪個操作應返回數據。在這種情況下,如果它是單個座標對象的數據,那麼使CoordinatesController#show動作有意義。這應該像這樣設置:

def show 
    @coordinate = Coordinate.find(params[:id]) 
    respond_to do |format| 
    format.html #defaults to rendering the /view/coordinates/show template 
    format.json { render json: @coordinate } 
    end 
end 

因此,這是軌道結束排序。

接下來就是從您的javascript調用上述操作。我打算用jquery來做,因爲它更簡單。

$.ajax({ 
    url: "/coordinates/"+coordinate_id, 
    dataType: "json", 
    success: function(data){ 
    //data is the data you got from the server, do something with it 
    } 
}); 

在這個例子中,你需要知道座標對象的id以便傳遞它。

+0

很棒!謝謝 – yolo

相關問題