1

Could someone explain the following scenario to me?

Let's say I have a a GeoJSON file with one Polygon feature containing just four coordinates:

var json = {
  "type": "FeatureCollection", 
  "features": [
    {
      "geometry": {
        "type": "Polygon", 
        "coordinates": [
          [
            [
              6.55757, 
              45.4283625
            ], 
            [
              6.50925565, 
              45.3728949
            ], 
            [
              6.5249137, 
              45.3728329
            ], 
            [
              6.52511385, 
              45.37276325
            ]
          ]
        ]
      }, 
      "type": "Feature", 
      "properties": {
        "uid": "fb3f3081-c6cf-4f64-8ccb-67918a3dbe84"
      }
    }
  ]
}

Now I want to project this to mercator and get the bounding box:

var projection = d3.geo.mercator()
.scale(1)
.precision(0);

var path = d3.geo.path()
.projection(projection);

var pathBounds = path.bounds(json.features[0]);
var geoBounds = d3.geo.bounds(json.features[0]);

json.features[0].geometry.coordinates[0].map(function(d) {
    console.log("projection:", projection(d)[0], projection(d)[1]);
});

console.log('path.bounds:', pathBounds[0][0], pathBounds[0][1])
console.log('path.bounds:', pathBounds[1][0], pathBounds[1][1])

console.log('d3.geo.bounds:', geoBounds[0][0], geoBounds[0][1])
console.log('d3.geo.bounds:', geoBounds[1][0], geoBounds[1][1])

The result is less than intuitive. The path's bounding box is way larger than any of the projected points and the geo bounding box is [[-180,-90],[180,90]].

It looks like the polygon is being interpreted as being the whole world outside of the polygon. Is this expected? Why is it doing that instead of treating the polygon as just the area within the listed points?

Fiddle (turn on the debugger to see the console log):

https://jsfiddle.net/pkerpedjiev/emr2g4f8/

juniper-
  • 6,262
  • 10
  • 37
  • 65
  • The coordinates should be clockwise to be interpreted correctly. – Lars Kotthoff Nov 08 '15 at 19:22
  • Yup, right you are! Right under the *important* section in the documentation, where I was least likely to check. If you add it as an answer, I'll be happy to accept it. – juniper- Nov 08 '15 at 20:31

1 Answers1

3

The documentation says:

Important: the inside of a polygon is all points that the polygon winds around in a clockwise order.

If you reverse the order of your points, it should work correctly.

Lars Kotthoff
  • 107,425
  • 16
  • 204
  • 204