简体   繁体   中英

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

i'm working with one template that loads one map on homepage, it gets information from one js file(locations.js)

UPDATE

This code load 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"],

Now i want to load my map with informations from my database (postgres) using Rails

there is any way to get this informations into this locations.js file directly form postgres without have to change my templates code?

i'm not very good with development, so its easier if i make this location.js work different than some map gem =/

In order to get the information from the database you will need to use Ruby code, since your JS can't interpret Ruby there are a couple of ways you could go in this situation.

1) Render the data you want in a data HTML attribute on the page somewhere and grab that in your javascript file.

2) Use js.erb or render JS directly within your html.erb files.

I personally prefer to use the data attribute approach. Your template might look like this.

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

And in your js you could do (assuming you are using JQuery)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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