繁体   English   中英

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

[英]Rails - how to get information from database and put into javascript var

我正在使用一个模板在主页上加载一张地图,它从一个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)中加载信息来加载我的地​​图

有什么方法可以直接从postgres将此信息导入到locations.js文件中,而无需更改模板代码?

我对开发不是很好,所以如果我使location.js的工作方式不同于某些地图上的gem = /,那么操作起来会更容易

为了从数据库中获取信息,您将需要使用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'));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM