SmokeyG / What3Words-to-Easting_Norting

Convert a what3words address to GB Easting & Northing
MIT License
0 stars 0 forks source link

Cleaned up example #1

Open LiamMyles opened 3 years ago

LiamMyles commented 3 years ago

Here is the code I cleaned up.

The main thing I think you need to explore more is understanding how code gets executed in javascript.

Also, the use case for something like localstorage is often quite narrow, so if you find yourself looking to use it in this way again you might need to dig into other options first. I think in this case because the default behaviour of a form is to reload the page, it often isn't.

Anyway, I hope this helps 😁 - if you want to dig into this more feel free to respond to this GitHub thread or message me directly.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Easting & Northings Test</title>

    <script src="./what3words.js?key=0E3KN406"></script>
    <!--
    <script 
    src='./what3words.js?key=VFD2REF7'>
    </script>
    -->
  </head>
  <body>
    <p id="w3w"><strong>Best What 3 word address is:</strong><br /></p>
    <p id="nearest_place"><strong>Nearest Place:</strong><br /></p>
    <p id="country"><strong>Country:</strong><br /></p>
    <p id="easting"><strong>Easting</strong><br /></p>
    <p id="northing"><strong>Northing</strong><br /></p>

    <!-- Get User input and show results -->
    <form id="submit-form">
      <label for="all-words">First Word</label>
      <input
        type="text"
        id="all-words"
        name="all-words"
        value="spot.loose.puddles"
        placeholder="what.three.words"
        autofocus
      />

      <p>
        <button>Get what3words Address</button>
      </p>

      <p>
        <a id="geoViewLink" href="#" target="_blank">Goto Easting & Northing</a>
      </p>
    </form>

    <!-- Store What3Words address -->
    <script type="module">
      import OsGridRef, {
        LatLon,
      } from "https://cdn.jsdelivr.net/npm/geodesy@2.2.0/osgridref.js";

      // Function to get all 3 words and return them as an array (I removed the 3 inputs for just one)
      function getW3W(event) {
        const w3wFirst = document.getElementById("w3wFirst").value;
        const w3wSecond = document.getElementById("w3wSecond").value;
        const w3wThird = document.getElementById("w3wThird").value;
        return [w3wFirst, w3wSecond, w3wThird];
      }

      // Adds an event listener to the form
      document
        .querySelector("#submit-form")
        .addEventListener("submit", (event) => {
          // This will prevent the form from submitting and reloading the page
          event.preventDefault();

          // This is how you would use function with 3 inputs
          //   const words = getW3W().concat(".");

          // Get the value from the input and store it in a variable called words
          const words = document.querySelector("#all-words").value;

          // This little wrapping code just lets me use async/await which is a nicer way of writing .then()
          (async () => {
            // Get my auto suggested response
            const autoSuggestResponse = await what3words.api.autosuggest(
              words,
              {
                clipToCountry: ["GB"],
                nResults: 5,
              }
            );

            // Display returned results for end user
            document
              .getElementById("w3w")
              // Append the result directly onto the end of the element
              .append(autoSuggestResponse.suggestions[0].words);

            document
              .getElementById("nearest_place")
              .append(autoSuggestResponse.suggestions[0].nearestPlace);

            document
              .getElementById("country")
              .append(autoSuggestResponse.country);

            // Retrieve the cords from the what 3 words api
            const w3wCoordinates = await what3words.api.convertToCoordinates(
              words
            );

            // Use the cords convert them to this grid format
            const grid = new LatLon(
              w3wCoordinates.coordinates.lat,
              w3wCoordinates.coordinates.lng
            ).toOsGrid(LatLon.datums.OSGB36);

            // Append the results of this grid format
            document.getElementById("easting").append(grid.easting);
            document.getElementById("northing").append(grid.northing);
          })();
        });
    </script>
  </body>
</html>
SmokeyG commented 3 years ago

This is brilliant Liam. Thank you very much for your hard work. I doubt I would've ever gotten to this stage. I will learn JS! :) As for delving deeper into the code, my novice input has not yet discovered half of the js you have used above. I will however, give it a try.

I think I can see how to add the words as separate input boxes, but I'm not sure how to get the link to work correctly. I have tried previously using the # in the, but I've never got it to work correctly, yet I'll git it a go.

Finally for this stint, I see the append is being used when using the getElementbyId. To help end users use a clean form, would you normally go with a button to clear the entries, or something to clear the entries on load/refresh of the page?

LiamMyles commented 3 years ago

No worries Dave, hopefully, this example gives you something to reference that you already mostly understand.

I'm not really sure what you mean by "Get the link to work correctly". If you elaborate on what you are trying to link to I might get a better idea.

If you want to clear the form you could use something like From.reset() check out the docs for from.reset for more details.

But also refreshing the page will yield similar results. But honestly, as a basic thing, you could leave it for someone to fill it in and submit it a second time.