I decided this week that I'd like to learn Node.js (I'm not a programmer). I've been having a lot of fun with it so far but I'm stuck at the moment.
I've created a basic app using Express. Let's say I have a route /locations. I set my get request to render the related view and to find (using Mongoose's .find method) all docs in my location model. I know I can pass the docs to the view like this:
app.get('/locations', function(req, res) {
Location.find({}, function(err, docs) {
res.render('locations/index', {
title: 'Locations',
user: req.user,
docs: docs
});
});
});
I can then, for example, access the results in the (Jade) view and list them by doing something like:
if(docs.length)
each location in docs
p #{location.name} is at #{location.coordinates}
I want to add all these locations (using coordinates stored with each 'location') to a Google Map. I have an example map displaying on the view using the following script in the head, taken from the Google Maps API documentation.
function initialize() {
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var mapOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
title: "Hello World!"
});
marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
I figured where the marker variable is created then set I could loop through my 'docs' and create and set a marker for each location stored in my database. That said, I'm too new to this and I can't seem to figure out how to do it as the script in the head can't access the 'docs' that I've passed to the view.
Any advice? Thanks in advance, it's much appreciated.
I JSON.stringify()
any objects that my client scripts need and insert it as HTML5 data-whatever
attributes.
For example:
//app.js
app.get('/map', function(req, res){
var data = {
id: '1234',
LL: {
lat: 42.1,
lng: 80.8,
};
res.locals.docsJSON = JSON.stringify([data]);
res.render('locations/index');
});
//jade
!!!
html
body(data-locations=locals.docsJSON)
script
var docs = JSON.parse($('body').attr('data-locations'));
console.log(docs[0].LL);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With