Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <h2><a href="https://mgrs-mapper.com">MGRS-Mapper.com</a></h2>
<div id="mapid"></div>
<h1>Corner Coords:</h1>
<pre></pre>

              
            
!

CSS

              
                #mapid {
  height: 800px;
  width: 800px;
  float: left;
}
h2 {
  font-family: Arial;
}
h1 {
  text-align: center;
  font-family: Arial;
}
pre {
  float: right; 
  width: 600px;
  white-space: pre-wrap;
  word-break: keep-all;
  border: 1px dashed black;
  padding: 20px;
}

              
            
!

JS

              
                const map = L.map("mapid").setView([43.7, -75.6], 6);
const myLayer = L.tileLayer(
  "https://c.tile.openstreetmap.org/{z}/{x}/{y}.png",
  {
    maxZoom: 18,
    id: "osm_map"
  }
).addTo(map);

myLayer.on("tileerror", function(error, tile) {
  console.log(error);
  console.log(tile);
  myLayer.addTo(map);
});

// https://gis.stackexchange.com/questions/287051/how-to-check-if-geojson-feature-is-in-rectangular-shape-and-find-corner-points
const getCornerPts = (turfInputPolygon, threshold = 1) => {
  let rightAngles = 0;
  let sumAngles = 0;
  const cornerPts = [];
  let turfPolygon = turfInputPolygon;

  if (turf.booleanClockwise(turf.polygonToLine(turfPolygon).features[0])) {
    turfPolygon = turf.rewind(turfPolygon);
  }

  const turfPolygonPts = turf.explode(turfPolygon);
  turfPolygonPts.features.push(turfPolygonPts.features[1]);

  for (let i = 1, len = turfPolygonPts.features.length; i < len - 1; i++) {
    const b1 = turf.bearing(
      turfPolygonPts.features[i - 1],
      turfPolygonPts.features[i]
    );
    const b2 = turf.bearing(
      turfPolygonPts.features[i],
      turfPolygonPts.features[i + 1]
    );
    const angle = Math.min((b1 - b2 + 360) % 360, (b2 - b1 + 360) % 360);
    sumAngles += angle;
    if (90 - threshold <= angle && angle <= 90 + threshold) {
      rightAngles++;
      cornerPts.push(turfPolygonPts.features[i]);
    }
  }
  return rightAngles == 4 &&
    (360 - threshold <= sumAngles && sumAngles <= 360 + threshold)
    ? cornerPts
    : false;
};

// https://ourcodeworld.com/articles/read/278/how-to-split-an-array-into-chunks-of-the-same-size-easily-in-javascript
const chunkArray = (myArray, chunk_size) => {
  let index = 0;
  const arrayLength = myArray.length;
  const tempArray = [];
  for (index = 0; index < arrayLength; index += chunk_size) {
    const myChunk = myArray.slice(index, index + chunk_size);
    // Do something if you want with the group
    tempArray.push(myChunk);
  }
  return tempArray;
};

// https://gomakethings.com/how-to-add-a-new-item-to-an-object-at-a-specific-position-with-vanilla-js/
const addToObject = (obj, key, value, index) => {
  // Create a temp object and index variable
  const temp = {};
  let i = 0;
  // Loop through the original object
  for (const prop in obj) {
    if (obj.hasOwnProperty(prop)) {
      // If the indexes match, add the new item
      if (i === index && key && value) {
        temp[key] = value;
      }
      // Add the current item in the loop to the temp obj
      temp[prop] = obj[prop];
      // Increase the count
      i++;
    }
  }
  // If no index, add to the end
  if (!index && key && value) {
    temp[key] = value;
  }
  return temp;
};

// Create an empty object to hold our valid JSON once completed
let finalObject = {};
// Create an empty array to collect grid coordinates and properties
const arr8 = [];

// Fetch the GeoJSON file and format it
fetch("https://api.jsonbin.io/b/5ddd1a7c040d843991f9652e")
  .then(res => res.json())
  .then(data => {
    for (let i = 0; i < data.features.length; i++) {
      // Clean up the GeoJSON files, replace "Polygon" with "MultiPolygon" and encapsulate the coordinates in another array
      Object.assign(data.features[i].geometry, {
        type: "MultiPolygon",
        coordinates: [data.features[i].geometry.coordinates]
      });
      // Grab the properties key so we can append it to our empty array
      const properties = data.features[i].properties;
      // Turf.js formatting
      const arrMultiPolygon = data.features[i].geometry.coordinates;
      const multiPolygon = turf.multiPolygon(arrMultiPolygon);
      // Get the latlng coordinates for the corners of each 100K grid square of the GZD
      getCornerPts(multiPolygon, 3).forEach(e => {
        // GeoJSON formats latitude-longitude backwards
        const gg = new L.LatLng(
          e.geometry.coordinates[1],
          e.geometry.coordinates[0]
        );
        // Push these new coordinates to the empty array
        arr8.push(gg);
      });
      // Pushes the properties value to each matching coordinates boundaries array
      if (i % 1 === 0) {
        arr8.push(properties);
      }
    }
  })
  .then(() => {
    // Split in group of 5 items (4 arrays of the coordinates of each grid square corner and 1 object containing it's properties)
    const result = chunkArray(arr8, 5);
    // Now let's build the grid
    result.forEach(e => {
      // Loop over the first 4 items in the array to create the grid, skip the 5th since it's just property values
      const grids100K = new L.polygon([e[0], e[1], e[2], e[3]], {
        fillColor: "#ff7800",
        weight: 2,
        stroke: true,
        color: "black",
        fillOpacity: 0.2,
        noClip: true,
        smoothFactor: 1,
        lineCap: "square",
        lineJoin: "miter"
      });
      // Add the grids to the map for validation
      grids100K.addTo(map);
      // Create a new object of the output so I can copy it's values for later use
      const completedObj = {
        [e[4]["100kmSQ_ID"]]: {
          topLeft: e[0],
          topRight: e[3],
          bottomRight: e[2],
          bottomLeft: e[1]
        }
      };
      // Add the completed object to the final object
      finalObject = addToObject(
        finalObject,
        Object.keys(completedObj),
        Object.values(completedObj)
      );
    });
    return finalObject;
  })
  .then(finalObject => {
    // Copy the completed object values :)
    console.log(JSON.stringify(finalObject));
    document.querySelector('pre').innerHTML = JSON.stringify(finalObject);
  })
  .catch(err => console.error(err));

//*********************************************************************//
//      CHECK CONSOLE FOR THE COORDINATES OF THE GRID SQUARE CORNERS   //
//*********************************************************************//
              
            
!
999px

Console