Imagine that you need to share some information from any path that you made in one map.
Google Maps allows you to draw it in a great way: You can just pick your set of waypoints, create a path using Directions with them and off you go!
But, what about sharing?
With MeteorJS, we have the ability to sync and present this data in real time to all clients connected to our service.
Combining MeteorJS potential and Google Maps possibilities it's easy to implement one way to draw and display your path to all users in only a few lines like this:
Coords = new Meteor.Collection("Coords");
pointsArr = new Array();
var allCoords = Coords.find();
allCoords.forEach(function (coord) {
// Add coordinates into the array
var latlng = new google.maps.LatLng(coord.lat, coord.lng);
pointsArr.push(latlng);
});
var origin = pointsArr[0];
var end = pointsArr[pointsArr.length - 1];
var waypointsArr = new Array();
if (pointsArr.length > 2) {
pointsArr.forEach(function (item) {
if (origin != item && end != item) {
waypointsArr.push({'location': item});
}
});
For now we have declared one Meteor 'Collection' to store all selected points as coordinates, we use this information to draw the path in the map web as soon as our page is loaded.
Then we add some code to add a point from the map into this collection whenever we detect a click event on it.
Hey, this is not reactive!
But wait, there's a problem: We have ready a little demo which can store paths and display them in your browser, but it's not reactive yet so the other clients can't get the updates!
The main reason for it is this information is stored in the database but it must be sent to other clients to be drawn in their browsers. But we are almost there: It's now when Meteor Tracker comes to help:
Tracker.autorun(function () {
if (Coords.find().count()) {
var allCoords = Coords.find();
pointsArr = new Array();
allCoords.forEach(function (coord) {
// Add coordinates into the array
var latlng = new google.maps.LatLng(coord.lat, coord.lng);
pointsArr.push(latlng);
});
// Draw path in the map
drawPath();
}
else {
// To clear
if(directionsDisplay) {
directionsDisplay.setMap(null);
directionsDisplay.setPanel(null);
}
}
});
Tracker allows us to put some code into the autorun callback. This code is executed whenever a change happens, and it's in there where we have to call our function to redraw the path using the new dataset we just were notified about.
Now we have a reactive interface to share paths with Google Maps in real time using only a few lines of code. Great stuff! Thank you Meteor!