首页 文章

rails将数据库vlaue发送到javascript

提问于
浏览
0

我在rails 3.2中有以下javascript代码 .

function initialize(){var myLatLng = new google.maps.LatLng(34.553366482,49.783977595); var mapOptions = {zoom:12,center:myLatLng,mapTypeId:google.maps.MapTypeId.TERRAIN};

var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);

    var flightPlanCoordinates = [
        new google.maps.LatLng(34.553366482, 49.783977595),
        new google.maps.LatLng(34.554122088, 49.783895487),
        new google.maps.LatLng(34.554483305, 49.783853715),
        new google.maps.LatLng(34.555332372, 49.783720553),

        new google.maps.LatLng(34.556189752, 49.783658072),
        new google.maps.LatLng(34.556664709, 49.783605137),
        new google.maps.LatLng(34.556769403, 49.783602219),
        new google.maps.LatLng(34.556787772, 49.783469404),

        new google.maps.LatLng(34.556793727, 49.783317126),
        new google.maps.LatLng(34.555050604, 49.783479752),
        new google.maps.LatLng(34.554290633, 49.783555281),
        new google.maps.LatLng(34.55376046, 49.783620191),

        new google.maps.LatLng(34.553413552, 49.783659434),
        new google.maps.LatLng(34.553275583, 49.783705246),
        new google.maps.LatLng(34.553366482, 49.783977595),

    ];
    var flightPath = new google.maps.Polyline({
      path: flightPlanCoordinates,
      strokeColor: '#FF0000',
      strokeOpacity: 1.0,
      strokeWeight: 2
    });

    flightPath.setMap(map);
  }

</script>

这是一种在谷歌 Map 上显示点的方式 . 我想从数据库中获取积分并发送到javascript . 我怎么能在循环中做到这一点?

1 回答

  • 0

    您可以在其中一个rails视图中创建一个javascript变量(json更具体),以便上面的脚本可以使用它 .

    在控制器/型号中:

    @coordinates = Coordinates(..your query...).get_json
    

    在您的视图中,这些点将显示,取决于您是否使用erb或haml,执行:

    HAML:

    :javascript
     var coords = "#{@coordinates.to_json}"
    

    厄尔布:

    <script type="text/javascript">
      var coords = "<%= escape_javascript(@coordinates.to_json)%>"
    </script>
    

    现在,您可以在上面的flightPlanCoordinates中迭代coords json并制作标记 .

相关问题