Rails - 如何从数据库中获取信息并放入javascript var

时间:2015-03-29 16:29:05

标签: javascript ruby-on-rails postgresql dictionary

我正在使用一个在主页上加载一个地图的模板,它从一个js文件(locations.js)获取信息

更新

此代码加载locations.js

function createHomepageGoogleMap(_latitude,_longitude){
setMapHeight();
if( document.getElementById('map') != null ){
    $.getScript("assets/js/locations.js", function(){
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 12,
            scrollwheel: false,
            center: new google.maps.LatLng(_latitude, _longitude),
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            styles: mapStyles
        });
        var i;
        var newMarkers = [];
        for (i = 0; i < locations.length; i++) {
            var pictureLabel = document.createElement("img");
            pictureLabel.src = locations[i][7];
            var boxText = document.createElement("div");
            infoboxOptions = {
                content: boxText,
                disableAutoPan: false,
                //maxWidth: 150,
                pixelOffset: new google.maps.Size(-100, 0),
                zIndex: null,
                alignBottom: true,
                boxClass: "infobox-wrapper",
                enableEventPropagation: true,
                closeBoxMargin: "0px 0px -8px 0px",
                closeBoxURL: "assets/img/close-btn.png",
                infoBoxClearance: new google.maps.Size(1, 1)
            };
            var marker = new MarkerWithLabel({
                title: locations[i][0],
                position: new google.maps.LatLng(locations[i][3], locations[i][4]),
                map: map,
                icon: 'assets/img/marker.png',
                labelContent: pictureLabel,
                labelAnchor: new google.maps.Point(50, 0),
                labelClass: "marker-style"
            });
            newMarkers.push(marker);
            boxText.innerHTML =
                '<div class="infobox-inner">' +
                    '<a href="' + locations[i][5] + '">' +
                    '<div class="infobox-image" style="position: relative">' +
                    '<img src="' + locations[i][6] + '">' + '<div><span class="infobox-price">' + locations[i][2] + '</span></div>' +
                    '</div>' +
                    '</a>' +
                    '<div class="infobox-description">' +
                    '<div class="infobox-title"><a href="'+ locations[i][5] +'">' + locations[i][0] + '</a></div>' +
                    '<div class="infobox-location">' + locations[i][1] + '</div>' +
                    '</div>' +
                    '</div>';
            //Define the infobox
            newMarkers[i].infobox = new InfoBox(infoboxOptions);
            google.maps.event.addListener(marker, 'click', (function(marker, i) {
                return function() {
                    for (h = 0; h < newMarkers.length; h++) {
                        newMarkers[h].infobox.close();
                    }
                    newMarkers[i].infobox.open(map, this);
                }
            })(marker, i));

        }
        var clusterStyles = [
            {
                url: 'assets/img/cluster.png',
                height: 37,
                width: 37
            }
        ];
        var markerCluster = new MarkerClusterer(map, newMarkers, {styles: clusterStyles, maxZoom: 15});
        $('body').addClass('loaded');
        setTimeout(function() {
            $('body').removeClass('has-fullscreen-map');
        }, 1000);
        $('#map').removeClass('fade-map');

        //  Dynamically show/hide markers --------------------------------------------------------------

        google.maps.event.addListener(map, 'idle', function() {

            for (var i=0; i < locations.length; i++) {
                if ( map.getBounds().contains(newMarkers[i].getPosition()) ){
                    // newMarkers[i].setVisible(true); // <- Uncomment this line to use dynamic displaying of markers

                    //newMarkers[i].setMap(map);
                    //markerCluster.setMap(map);
                } else {
                    // newMarkers[i].setVisible(false); // <- Uncomment this line to use dynamic displaying of markers

                    //newMarkers[i].setMap(null);
                    //markerCluster.setMap(null);
                }
            }
        });

        // Function which set marker to the user position
        function success(position) {
            var center = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
            map.panTo(center);
            $('#map').removeClass('fade-map');
        }

    });
    // Enable Geo Location on button click
    $('.geo-location').on("click", function() {
        if (navigator.geolocation) {
            $('#map').addClass('fade-map');
            navigator.geolocation.getCurrentPosition(success);
        } else {
            error('Geo Location is not supported');
        }
    });
}

}

var locations = [


['2479 Murphy Court', "Minneapolis, MN 55402", "$36,000", 48.864352, 2.257218, "property-detail.html", "../assets/img/properties/property-11.jpg", "../assets/img/property-types/vineyard.png"],
['3398 Lodgeville Road', "Golden Valley, MN 55427", "$28,000", 48.858648, 2.273526, "property-detail.html", "../assets/img/properties/property-12.jpg", "../assets/img/property-types/warehouse.png"],
['2479 Murphy Court', "Minneapolis, MN 55402", "$36,000", 48.856277, 2.264256, "property-detail.html", "../assets/img/properties/property-13.jpg", "../assets/img/property-types/industrial-site.png"],

现在我想使用Rails

从我的数据库(postgres)加载我的地​​图信息

有什么方法可以直接将这些信息放到这个locations.js文件中,而不必更改我的模板代码吗?

我对开发不是很好,所以如果我使这个location.js工作不同于某些地图gem = /

它会更容易

1 个答案:

答案 0 :(得分:0)

为了从数据库中获取信息,您需要使用Ruby代码,因为您的JS无法解释Ruby,在这种情况下您可以采用以下几种方式。

1)在页面上的某个数据HTML属性中渲染您想要的数据并将其存储在您的javascript文件中。

2)在你的html.erb文件中直接使用js.erb或渲染JS。

我个人更喜欢使用数据属性方法。您的模板可能如下所示。

<div class="map" data-map="<%= ['2479 Murphy Court'].to_json %>
  # stuff
</div>

在你的js中你可以做(​​假设你正在使用JQuery)

var locations = JSON.parse($('.map').data('map'));