Now the function that we're about to create is going to look really similar to this, we're going to take some data in and we're going to return an object. The big difference is that we'll be generating that URL as well. Instead of from, text, and createdAt, we're going to have from, URL, and createdAt.
We can make a new variable, we can call this variable generateLocationMessage, and we can go ahead and set it equal to a function that takes those three arguments from, latitude, and longitude:
var generateLocationMessage = (from, latitude, longitude)
Now we can finish off the arrow function (=>) adding the arrow and our curly braces, and inside of here we can get started by returning the empty object:
var generateLocationMessage = (from, latitude, longitude) => {
return {
};
};
Now we're going to set up those three properties from property, the URL property and createdAt. Here from is going to be easy; just like we do for generateMessage, we're simply going to reference the argument. The URL one is going to be a little trickier; for now we'll set that equal to an empty template string, we'll come back to it in a moment. And finally, createdAt, we've done that before; we're going to set it equal to a timestamp by getting a new Date and calling getTime:
var generateLocationMessage = (from, latitude, longitude) => {
return {
from,
from,
url: ``,
createdAt: new Date().getTime()
};
};
Now for the URL we're going to need to use that exact same format that we just typed into the browser, https://www.google.com/maps. Then we've got to set up our query parameter, adding our question mark and our q param, setting it equal to the latitude followed by a comma, and followed by the longitude. We're going to inject the latitude, add a comma, and then inject the longitude:
var generateLocationMessage = (from, latitude, longitude) => {
return {
from,
url: `https://www.google.com/maps?q=${latitude},${longitude}`,
createdAt: new Date().getTime()
};
};
Now we're done! generateLocationMessage is going to work as expected, although you will be writing a test case a little later on. For now we can simply export it. I'm going to export generateLocationMessage, like this:
var generateLocationMessage = (from, latitude, longitude) => {
return {
from,
url: `https://www.google.com/maps?q=${latitude},${longitude}`,
createdAt: new Date().getTime()
};
};
module.exports = {generateMessage, generateLocationMessage};
Now the data is going to flow from the client by calling emit, passing in generateLocationMessage. We're going to get the latitude and longitude. Over inside the server.js, we are then going to emit the newLocationMessage event with the object that we just defined over inside generateLocationMessage:
socket.on('createLocationMessage', (coords) => {
io.emit('newLocationMessage', generateLocationMessage('Admin', coords.latitude, coords.longitude));
});