123

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

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

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

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.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <!--

Dont't forget to include the required css and javascript:
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.css" />
<script src="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.js"></script>

-->
<div id="map"></div>
            
          
!
            
              body,
html {
  height: 100%;
}
  
#map {
  width: 100%;
  height: 100%;
}
            
          
!
            
              // dependencies and utilities

function geoBoundingBox (gj) {
  var coords, bbox

  if (!gj.hasOwnProperty('type')) return

  coords = getCoordinatesDump(gj)
  bbox = [Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY,
          Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY]
  return coords.reduce(function(prev,coord) {
    return [
      Math.min(coord[0], prev[0]),
      Math.min(coord[1], prev[1]),
      Math.max(coord[0], prev[2]),
      Math.max(coord[1], prev[3])
    ]
  }, bbox)
};

function getCoordinatesDump (gj) {
  var coords
 
  if (gj.type == 'Point') {
    coords = [gj.coordinates]
  } else if (gj.type == 'LineString' || gj.type == 'MultiPoint') {
    coords = gj.coordinates
  } else if (gj.type == 'Polygon' || gj.type == 'MultiLineString') {
    coords = gj.coordinates.reduce(function(dump, part) {
      return dump.concat(part);
    }, [])
  } else if (gj.type == 'MultiPolygon') {
    coords = gj.coordinates.reduce(function(dump, poly) {
      return dump.concat(poly.reduce(function(points,part) {
        return points.concat(part)
      },[]))
    },[])
  } else if (gj.type == 'Feature') {
    coords =  getCoordinatesDump(gj.geometry)
  } else if (gj.type == 'GeometryCollection') {
    coords = gj.geometries.reduce(function(dump, g) {
      return dump.concat(getCoordinatesDump(g))
    },[])
  } else if (gj.type == 'FeatureCollection') {
    coords = gj.features.reduce(function(dump, f) {
      return dump.concat(getCoordinatesDump(f))
    },[])
  }
  return coords
}

function createPolygonFromBounds (latLngBounds) {
  var center = latLngBounds.getCenter()
  var latlngs = []

  latlngs.push(latLngBounds.getSouthWest());//bottom left
  latlngs.push({ lat: latLngBounds.getSouth(), lng: center.lng })//bottom center
  latlngs.push(latLngBounds.getSouthEast()) // bottom right
  latlngs.push({ lat: center.lat, lng: latLngBounds.getEast() })// center right
  latlngs.push(latLngBounds.getNorthEast());// top right
  latlngs.push({ lat: latLngBounds.getNorth(), lng: map.getCenter().lng }) // top center
  latlngs.push(latLngBounds.getNorthWest()) // top left
  latlngs.push({ lat: map.getCenter().lat, lng: latLngBounds.getWest() }) // center left

  return new L.polygon(latlngs)
}

// copied from @mapbox/tilebelt

var d2r = Math.PI / 180,
    r2d = 180 / Math.PI;

/**
 * Get the bbox of a tile
 *
 * @name tileToBBOX
 * @param {Array<number>} tile
 * @returns {Array<number>} bbox
 * @example
 * var bbox = tileToBBOX([5, 10, 10])
 * //=bbox
 */
function tileToBBOX(tile) {
    var e = tile2lon(tile[0] + 1, tile[2]);
    var w = tile2lon(tile[0], tile[2]);
    var s = tile2lat(tile[1] + 1, tile[2]);
    var n = tile2lat(tile[1], tile[2]);
    return [w, s, e, n];
}

/**
 * Get a geojson representation of a tile
 *
 * @name tileToGeoJSON
 * @param {Array<number>} tile
 * @returns {Feature<Polygon>}
 * @example
 * var poly = tileToGeoJSON([5, 10, 10])
 * //=poly
 */
function tileToGeoJSON(tile) {
    var bbox = tileToBBOX(tile);
    var poly = {
        type: 'Polygon',
        coordinates: [[
            [bbox[0], bbox[1]],
            [bbox[0], bbox[3]],
            [bbox[2], bbox[3]],
            [bbox[2], bbox[1]],
            [bbox[0], bbox[1]]
        ]]
    };
    return poly;
}

function tile2lon(x, z) {
    return x / Math.pow(2, z) * 360 - 180;
}

function tile2lat(y, z) {
    var n = Math.PI - 2 * Math.PI * y / Math.pow(2, z);
    return r2d * Math.atan(0.5 * (Math.exp(n) - Math.exp(-n)));
}

// TODO: update this to support multiPolygon as well
// TODO: return a list of points that intersect instead
function polyIntersectsWithMultiPoly (poly, multiPoly) {
  var intersects = false

  poly.coordinates.forEach(function (coord1) {
    coord1.forEach(function (coord2) {
      const polyPoint = turf.point(coord2)

      if (turf.inside(polyPoint, multiPoly) && !intersects) {
        intersects = true
      }
    })
  })

  return intersects
}

// ------------------------------- actual issue

var map = L.map('map', {
  center: [36.1714895, -120.201561],
  zoom: 15,
  maxZoom: 21,
})

console.log('map', map.options)


// Create a Tile Layer and add it to the map
// var tiles = new L.tileLayer('http://{s}.tile.stamen.com/watercolor/{z}/{x}/{y}.png').addTo(map)

var tiles = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map)

var shape = {
  "type": "Feature",
  "geometry": {
    "type":"MultiPolygon",
    "coordinates":[
      [
        [
          [
            -120.210483180564,
            36.1733407559931
          ],
          [
            -120.208957248083,
            36.1736847467392
          ],
          [
            -120.207629508842,
            36.1739369696058
          ],
          [
            -120.206294631218,
            36.1742082281604
          ],
          [
            -120.204985927664,
            36.1744794867151
          ],
          [
            -120.203515420763,
            36.1747983344899
          ],
          [
            -120.202270962657,
            36.1750529368174
          ],
          [
            -120.200993192097,
            36.1752789856131
          ],
          [
            -120.200326943015,
            36.1754360300395
          ],
          [
            -120.19920383742,
            36.175657319913
          ],
          [
            -120.198002209612,
            36.1759047838576
          ],
          [
            -120.196786305038,
            36.1761546272631
          ],
          [
            -120.195625128068,
            36.1763806760586
          ],
          [
            -120.195101646646,
            36.1764187474349
          ],
          [
            -120.195032642277,
            36.1764139885128
          ],
          [
            -120.194998495206,
            36.1764258657549
          ],
          [
            -120.194942222759,
            36.1763878144417
          ],
          [
            -120.194449674331,
            36.1758857481695
          ],
          [
            -120.193545479148,
            36.1749767940652
          ],
          [
            -120.192724565102,
            36.1741035318761
          ],
          [
            -120.192734082946,
            36.1739464874497
          ],
          [
            -120.192661603695,
            36.1739393828761
          ],
          [
            -120.192647457341,
            36.1734810410078
          ],
          [
            -120.192648435218,
            36.1731153152421
          ],
          [
            -120.192654746354,
            36.173069109145
          ],
          [
            -120.192648176705,
            36.1720294621949
          ],
          [
            -120.19265080181,
            36.1704700949203
          ],
          [
            -120.192648176705,
            36.1685097727573
          ],
          [
            -120.192643663427,
            36.1666986492261
          ],
          [
            -120.192638904505,
            36.1666248859348
          ],
          [
            -120.193309912509,
            36.1666225064739
          ],
          [
            -120.197186054487,
            36.1666034707858
          ],
          [
            -120.199351364003,
            36.1666106091687
          ],
          [
            -120.20003188985,
            36.1665939529418
          ],
          [
            -120.200986053714,
            36.1665939529418
          ],
          [
            -120.201055087253,
            36.1665531949778
          ],
          [
            -120.201302522027,
            36.1665558815657
          ],
          [
            -120.201426254,
            36.16668437246
          ],
          [
            -120.201602334114,
            36.1667343411411
          ],
          [
            -120.201666579561,
            36.1668342785033
          ],
          [
            -120.201816485605,
            36.1668771088014
          ],
          [
            -120.201878351591,
            36.1668556936525
          ],
          [
            -120.202006842485,
            36.1668771088014
          ],
          [
            -120.202009267592,
            36.1665995234639
          ],
          [
            -120.202144851224,
            36.1666034707858
          ],
          [
            -120.203731951714,
            36.1666010913248
          ],
          [
            -120.205077087342,
            36.166589594439
          ],
          [
            -120.206254180381,
            36.1665939529418
          ],
          [
            -120.207510535792,
            36.1665891940198
          ],
          [
            -120.207610473154,
            36.1665987118637
          ],
          [
            -120.208845413416,
            36.1669318364046
          ],
          [
            -120.210092250983,
            36.1671840592712
          ],
          [
            -120.210301643552,
            36.1673125501656
          ],
          [
            -120.210299264091,
            36.1674386615989
          ],
          [
            -120.210422996063,
            36.1674505589039
          ],
          [
            -120.210472964744,
            36.1674457999819
          ],
          [
            -120.210469095648,
            36.1697633885423
          ],
          [
            -120.210356371155,
            36.1697848101506
          ],
          [
            -120.210301643552,
            36.1698038458387
          ],
          [
            -120.210294505169,
            36.1698323993706
          ],
          [
            -120.210349232772,
            36.1698657118247
          ],
          [
            -120.210468829499,
            36.1699228119854
          ],
          [
            -120.210483180564,
            36.1733407559931
          ]
        ]
      ]
    ]
  }
}

var zoom = 19

var boundCoords = geoBoundingBox(shape)
var boundLatLngs = new L.latLngBounds(L.GeoJSON.coordsToLatLngs([[boundCoords[0], boundCoords[1]], [boundCoords[2], boundCoords[3]]]))
var boundShape = createPolygonFromBounds(boundLatLngs).setStyle({ color: 'yellow' })

var boundNorthEastCorner = boundLatLngs.getNorthEast()
var boundSouthWestCorner = boundLatLngs.getSouthWest()

var boundNorthWestCorner = boundLatLngs.getNorthWest()
var boundSouthEastCorner = boundLatLngs.getSouthEast()

console.log('bound corners [ne, sw, nw, se]', boundNorthEastCorner, boundSouthWestCorner, boundNorthWestCorner, boundSouthEastCorner)

var boundPoints = L.bounds(
  map.project(boundNorthWestCorner, zoom),
  map.project(boundSouthEastCorner, zoom)
)

var boundNorthWestMarker = L.marker(boundNorthWestCorner, { title: 'NW' })
var boundSouthEastMarker = L.marker(boundSouthEastCorner, { title: 'SE' })

console.log('boundaries', boundCoords, boundLatLngs, boundPoints, boundShape)
console.log('--- north west', boundNorthWestCorner)
console.log('--- south east', boundSouthEastCorner)

// @see https://gist.github.com/mourner/8825883
var tileBounds = L.bounds(
  boundPoints.min.divideBy(tiles.getTileSize().x).floor(),
  boundPoints.max.divideBy(tiles.getTileSize().x).floor()
)

console.log('tile bounds', tileBounds)

// var tileBoundsShape = createPolygonFromBounds(tileBounds).setStyle({ color: 'brown' })

// ------------------------------- intersection detection

// 1. avoid conversion altogether (try to stay with LatLng)
//  - probably not possible since we need to iterate through the coordinates (what would the base unit be?)
// 2. potentially use TurfJS http://turfjs.org/docs#squareGrid
// 3. look into vector math and calculus approaches to providing the intersection between the bbox and shape integrals as a grid of tiles
// 4. checkout https://github.com/tilemapjp/mbtiles.js/tree/master
// 5. write a custom CRS
// 6. check if the x/y values (before being converted back into lat/lng)
// 7. convert GeoJSON shape into x/y values
///   - convert x/y's that are scaled to tile boundaries into meters instead of the x/y (divided by 256)
//      * the problem is (likely) that we are checking tile indices and not x/y scaled to meters
//       - interestingly, these coordinates end up providing the correct result when `L.TileLayer.prototype.getTileUrl` is called
//    - ensure i/j is in meters

var dump = []

// TODO: test iterating through the width of a tile (in x/y) instead of tile indices
for (var j = tileBounds.min.y; j <= tileBounds.max.y; j += 1) {
  dump.push(new Array(tileBounds.max.y - tileBounds.min.y))

  for (var i = tileBounds.min.x; i <= tileBounds.max.x; i += 1) {
    var tilePoint = new L.Point(i, j) // RESEARCH: the x/y scaled to tile could be throwing this off
    // var tileLatLng = map.layerPointToLatLng(tilePoint) // FIXME: this value is experiencing drift!
    // var tileShape = { type: 'Point', coordinates: [tileLatLng.lng, tileLatLng.lat] }
    // var tileIntersects = gju.pointInPolygon(tileShape, shape)
    var tileShape = tileToGeoJSON([tilePoint.x, tilePoint.y, zoom])
    var tileIntersects = polyIntersectsWithMultiPoly(tileShape, shape)
    // var tileIntersects = turf.intersect(shape, tileShape)
 
    // console.log('\n--- tile lat/lng', tileLatLng)
    console.log('\n--- tile point', tilePoint)
    console.log('--- tile x/y (orig)', i, j)
    console.log('--- tile unprojected', map.unproject(tilePoint, 19))
    console.log('--- tile shape', tileShape)
    console.log('--- field shape', shape)
    console.log('--- tile pixel origin', map.getPixelOrigin(), map.unproject(map.getPixelOrigin()))
    console.log('--- intersects?', tileIntersects)
    
    L.geoJSON(tileShape, { style: { color: 'pink' }}).addTo(map)
 
    if (tileIntersects) {
      L.geoJSON(tileShape, { style: { color: 'teal' } }).addTo(map)
      // L.marker(tileLatLng, { title: 'Tile', style: { color: 'red' } })
      
      dump[j - tileBounds.min.y][i - tileBounds.min.x] = { tilePoint: tilePoint }//, tileLatLng: tileLatLng }
    }

    // FIXME: `tileLatLng` is drifting, causing `tileIntersects` to always be false
  }
}

// ---------------------------------- visualize the shapes

console.log('tile size', tiles.getTileSize().x)
console.log('tile bounds', tileBounds)
console.log('dump', dump)

var meta = {
  field: {
    bounds: boundCoords,
    shape: shape
  },
  tiles: {
    bounds: tileBounds,
    dimensions: {
      x: tiles.getTileSize().x,
      y: tiles.getTileSize().y
    }
  },
  zoom: zoom,
  dump: dump
}

console.log('meta', JSON.stringify(meta))

// boundNorthWestMarker.addTo(map)
// boundSouthEastMarker.addTo(map)
boundShape.addTo(map)

L.geoJSON(shape).addTo(map)
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.

Console