Edit me

This is based on Daniel Shiffman’s video tutorial on Working with Data and APIs in JavaScript.

Resource

Purpose

Step 1: Make sure geolocation service is available on client side.

if ("geolocation" in navigator) {
  console.log('geolocation is available');
} else {
  console.log('geolocation IS NOT available');
}

Step 2: Get the current position

Call the getCurrentPosition function which requires you to pass in a callback function that is executed when the position is ready to be retrieved.

if ("geolocation" in navigator) {
  console.log('geolocation is available');
  // get current position
  navigator.geolocation.getCurrentPosition(position => console.log(position.coords));
} else {
  console.log('geolocation IS NOT available');
  
}

Step 3: Write your position into DOM elements

if ("geolocation" in navigator) {
  console.log('geolocation is available');
  navigator.geolocation.getCurrentPosition(position => console.log(position.coords));
  const lat = position.coords.latitude;
  // Write to a DOM element
  document.getElementById('lat').textContent = lat.toFixed(2);
  const lon = position.coords.longitude;
   // Write to a DOM element
  document.getElementById('lon').textContent = lon.toFixed(2);
} else {
  console.log('geolocation IS NOT available');
}

Step 4: Have the server receive data from the client

app.post(path, callback [, callback ...])

Path: The path for which the middleware function is invoked;
callback: callback functions
Routes HTTP POST requests to the specified path with the specified callback functions.

app.post(path, callback [, callback …])

// api - setting up an application programming interface, can be any name
// The request variable refers to everything contained within the request, while the response a variable that we can use to send things back to the client
app.post('/api', (request, response) => {
  console.log(request);
});

Step 5: Have the client send data to the server

Move over to the client side and set up the POST itself using fetch(). Fetch the post over to /api endpoint.

if ("geolocation" in navigator) {
  console.log('geolocation is available');
  navigator.geolocation.getCurrentPosition(position => console.log(position.coords));
  const lat = position.coords.latitude;
  document.getElementById('lat').textContent = lat.toFixed(2);
  const lon = position.coords.longitude;
  document.getElementById('lon').textContent = lon.toFixed(2);
  // Make an object
  const data = { lat, lon };
  const options = {
    method: `POST`,
    // meta information
    headers: {
      // 
      'Content-Type': 'application/json'
    },
    // Take JavaScript object data and make it into a JSON string.
    body: JSON.stringify(data)


  };
  // Fetch the stuff from /api 
  // The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses
  fetch('/api', options); // to send a POST, we need a second argument here, options.
} else {
  console.log('geolocation IS NOT available');
}

Step 6: Teach the server to parse any incoming data as JSON

express.json([options])

This is a built-in middleware function in Express. It parses incoming requests with JSON payloads and is based on body-parser.

app.use(express.json({ limit: '1mb' }));

Step 7: Complete the request

When a GET request or a POST request is coming into the server, we should do something to complete it. To be a ‘polite’ server, it should send some response.

At a minimum, you should run this command:

response.end();

To make more sense, do this:

// make a variable
const data = request.body;
response.json({
  status: 'success',
  // send back the object data, for example
  latitude: data.lat,
  longitude: data.lon
})

Step 8:Handle the response from the server

In the client JS, the fetch() returns a promise. Let’s handle the response.

  1. First of all, make the callback function an async function to make your code more elegant.
    navigator.geolocation.getCurrentPosition(async position => {...};
    
  2. Fetch the response and pare it.
    navigator.geolocation.getCurrentPostion(async function => {
      ...
      const response = await fetch('/api', options);
      const responseJson = await response.json();
      console.log(responseJson);
      ...
    });
    
  3. Now, the response from the server is printed on the console. Console Printout;