Search code examples
node.jsexpress-handlebars

get data from nodejs to frontend js for google maps but stuck in retrieving it looking for ways to solve it


My NodeJS GET route:

router.get('/stores', function (req, res, next) {
errorMsg = req.flash('error')[0];
successMsg = req.flash('success')[0];

Product.find(function (err, products) {
    // console.log(products)
    res.render('admin/stores', {
        layout: 'admin-map.hbs',
        stores: products,
        errorMsg: errorMsg,
        GOOGLE_APIKEY: process.env.GOOGLE_APIKEY,
        noErrors: 1
    });
});

The route /stores returns json data which holds latitude and longitude and I want it in my script tag of map.html with loop, to render the pins on the map. Below, the script:

<!DOCTYPE html>
<html>

   <head>
   <script src = "https://maps.googleapis.com/maps/api/js"></script>

   <script>
     function loadMap() {
        alert(this.stores);
        var mapOptions = {
           center:new google.maps.LatLng(17.433053, 78.412172),
           zoom:5
        }

        var map = new google.maps.Map(document.getElementById("sample"),mapOptions);

        var marker = new google.maps.Marker({
           position: new google.maps.LatLng(17.433053, 78.412172),
           map: map,
           draggable:true,
           icon:'/scripts/img/logo-footer.png'
        });

        marker.setMap(map);

        var infowindow = new google.maps.InfoWindow({ });

        infowindow.open(map,marker);
     }
    </script>
    <!-- ... -->
    </head>
</html>

How can I do it?


Solution

  • the answer is inside fronted script i can have an object declared globally and this double flower brackets works fine with them

     <script>
         function loadMap() {
            alert(this.stores);
            var mapOptions = {
               center:new google.maps.LatLng(17.433053, 78.412172),
               zoom:5
            }
    
            var map = new google.maps.Map(document.getElementById("sample"),mapOptions);
          {{#each stores}}
            var marker = new google.maps.Marker({
               position: new google.maps.LatLng(17.433053, 78.412172),
               map: map,
               draggable:true,
               icon:'/scripts/img/logo-footer.png'
            });
    {{/each}}
    
            marker.setMap(map);
    
            var infowindow = new google.maps.InfoWindow({ });
    
            infowindow.open(map,marker);
         }
        </script>