utilizing point-in-poly but providing support for geojson polys and holes.
510749
function (point, geopoly) {
  var inside = 0;

  if(geopoly.type !== "Polygon" && geopoly.type !== "MultiPolygon") return false;

  var shape = geopoly.type === 'Polygon' ? [geopoly.coordinates] : geopoly.coordinates;
  shape.forEach(function (polygon) {
    polygon.forEach(function (ring) {
      if(pip([point.longitude, point.latitude], ring)) inside++;
    });
  });
  return inside % 2;
}
820787
function Primitive(geojson){
    if(geojson){
      switch (geojson.type) {
      case 'Point':
        return new Point(geojson);

      case 'MultiPoint':
        return new MultiPoint(geojson);

      case 'LineString':
        return new LineString(geojson);

      case 'MultiLineString':
        return new MultiLineString(geojson);

      case 'Polygon':
        return new Polygon(geojson);

      case 'MultiPolygon':
        return new MultiPolygon(geojson);

      case 'Feature':
        return new Feature(geojson);

      case 'FeatureCollection':
        return new FeatureCollection(geojson);

      case 'GeometryCollection':
        return new GeometryCollection(geojson);

      default:
        throw new Error("Unknown type: " + geojson.type);
      }
    }
  }
1136345
function(node) {
        var georssns = this.namespaces.georss;

        var locations = {components: []};
        var where = this.getElementsByTagNameNS(node, georssns, "where");
        if (where && where.length > 0) {
            if (!this.gmlParser) {
                this.initGmlParser();
            }
            for (var i=0, ii=where.length; i<ii; i++) {
                this.gmlParser.readChildNodes(where[i], locations);
            }
        }
        
        var components = locations.components;
        var point = this.getElementsByTagNameNS(node, georssns, "point");
        if (point && point.length > 0) {
            for (var i=0, ii=point.length; i<ii; i++) {
                var xy = OpenLayers.String.trim(
                            point[i].firstChild.nodeValue
                            ).split(/\s+/);
                if (xy.length !=2) {
                    xy = OpenLayers.String.trim(
                                point[i].firstChild.nodeValue
                                ).split(/\s*,\s*/);
                }
                components.push(new OpenLayers.Geometry.Point(xy[1], xy[0]));
            }
        }

        var line = this.getElementsByTagNameNS(node, georssns, "line");
        if (line && line.length > 0) {
            var coords;
            var p;
            var points;
            for (var i=0, ii=line.length; i<ii; i++) {
                coords = OpenLayers.String.trim(
                                line[i].firstChild.nodeValue
                                ).split(/\s+/);
                points = [];
                for (var j=0, jj=coords.length; j<jj; j+=2) {
                    p = new OpenLayers.Geometry.Point(coords[j+1], coords[j]);
                    points.push(p);
                }
                components.push(
                    new OpenLayers.Geometry.LineString(points)
                );
            }
        }        

        var polygon = this.getElementsByTagNameNS(node, georssns, "polygon");
        if (polygon && polygon.length > 0) {
            var coords;
            var p;
            var points;
            for (var i=0, ii=polygon.length; i<ii; i++) {
                coords = OpenLayers.String.trim(
                            polygon[i].firstChild.nodeValue
                            ).split(/\s+/);
                points = [];
                for (var j=0, jj=coords.length; j<jj; j+=2) {
                    p = new OpenLayers.Geometry.Point(coords[j+1], coords[j]);
                    points.push(p);
                }
                components.push(
                    new OpenLayers.Geometry.Polygon(
                        [new OpenLayers.Geometry.LinearRing(points)]
                    )
                );
            }
        }
        
        if (this.internalProjection && this.externalProjection) {
            for (var i=0, ii=components.length; i<ii; i++) {
                if (components[i]) {
                    components[i].transform(
                        this.externalProjection,
                        this.internalProjection
                    );
                }
            }
        }
        
        return components;
    }
365646
function( pointA, pointB ) {

	        return { x: pointB.x - pointA.x, y: -( pointB.y - pointA.y ) };
	    }
402362
function fromOverlaysToJSON_(geom) {
  var gtype = getGeometryType_(geom);
  var g, gs, i, pts;
  var json = '{';
  switch (gtype) {
  case GeometryType.POINT:
    g = isArray_(geom) ? geom[0] : geom;
    if (g instanceof G.Marker) {
      g = g.getPosition();
    }
    json += 'x:' + g.lng() + ',y:' + g.lat();
    break;
  case GeometryType.MULTIPOINT:
    pts = [];
    for (i = 0; i < geom.length; i++) {
      if (geom[i] instanceof G.Marker) {
        g = geom[i].getPosition();
      } else {
        g = geom[i];
      }
      pts.push('[' + g.lng() + ',' + g.lat() + ']');
    }
    json += 'points: [' + pts.join(',') + ']';
    break;
  case GeometryType.POLYLINE:
    // V3 does not support multiple paths yet
    pts = [];
    gs = isArray_(geom) ? geom : [geom];
    for (i = 0; i < gs.length; i++) {
      pts.push('[' + fromLatLngsToJSON_(gs[i].getPath()) + ']');
    }
    json += 'paths:[' + pts.join(',') + ']';
    break;
  case GeometryType.POLYGON:
    pts = [];
    g = isArray_(geom) ? geom[0] : geom;
    var paths = g.getPaths();
    for (i = 0; i < paths.getLength(); i++) {
      pts.push('[' + fromLatLngsToJSON_(paths.getAt(i), true) + ']');
    }
    json += 'rings:[' + pts.join(',') + ']';
    
    break;
  case GeometryType.ENVELOPE:
    g = isArray_(geom) ? geom[0] : geom;
    json += 'xmin:' + g.getSouthWest().lng() + ',ymin:' + g.getSouthWest().lat() + ',xmax:' + g.getNorthEast().lng() + ',ymax:' + g.getNorthEast().lat();
    break;
  }
  json += ', spatialReference:{wkid:4326}';
  json += '}';
  return json;
}
835140
function buildGeom(item, params) {
    var geom = {},
        attr;

    for(var gtype in params.geom) {
      var val = params.geom[gtype];

      // Geometry parameter specified as: {Point: 'coords'}
      if(typeof val === 'string' && item.hasOwnProperty(val)) {
        if(gtype === 'GeoJSON') {
          geom = item[val];
        } else {
          geom.type = gtype;
          geom.coordinates = item[val];
        }
      }

      /* Handle things like:
      Polygon: {
        northeast: ['lat', 'lng'],
        southwest: ['lat', 'lng']
      }
      */
      else if(typeof val === 'object' && !Array.isArray(val)) {
        /*jshint loopfunc: true */
        var points = Object.keys(val).map(function(key){
          var order = val[key];
          var newItem = item[key];
          return buildGeom(newItem, {geom:{ Point: order}});
        });
        geom.type = gtype;
        /*jshint loopfunc: true */
        geom.coordinates = [].concat(points.map(function(p){
          return p.coordinates;
        }));
      }

      // Geometry parameter specified as: {Point: ['lat', 'lng', 'alt']}
      else if(Array.isArray(val) && item.hasOwnProperty(val[0]) && item.hasOwnProperty(val[1]) && item.hasOwnProperty(val[2])){
        geom.type = gtype;
        geom.coordinates = [Number(item[val[1]]), Number(item[val[0]]),  Number(item[val[2]])];
      }

      // Geometry parameter specified as: {Point: ['lat', 'lng']}
      else if(Array.isArray(val) && item.hasOwnProperty(val[0]) && item.hasOwnProperty(val[1])){
        geom.type = gtype;
        geom.coordinates = [Number(item[val[1]]), Number(item[val[0]])];
      }

      // Geometry parameter specified as: {Point: ['container.lat', 'container.lng', 'container.alt']}
      else if(Array.isArray(val) && isNested(val[0]) && isNested(val[1]) && isNested(val[2])){
        var coordinates = [];
        for (var i = 0; i < val.length; i++) {	// i.e. 0 and 1
          var paths = val[i].split('.');
          var itemClone = item;
          for (var j = 0; j < paths.length; j++) {
            if (!itemClone.hasOwnProperty(paths[j])) {
              return false;
            }
            itemClone = itemClone[paths[j]];	// Iterate deeper into the object
          }
          coordinates[i] = itemClone;
        }
        geom.type = gtype;
        geom.coordinates = [Number(coordinates[1]), Number(coordinates[0]), Number(coordinates[2])];
      }

      // Geometry parameter specified as: {Point: ['container.lat', 'container.lng']}
      else if(Array.isArray(val) && isNested(val[0]) && isNested(val[1])){
        var coordinates = [];
        for (var i = 0; i < val.length; i++) {	// i.e. 0 and 1
          var paths = val[i].split('.');
          var itemClone = item;
          for (var j = 0; j < paths.length; j++) {
            if (!itemClone.hasOwnProperty(paths[j])) {
              return false;
            }
            itemClone = itemClone[paths[j]];	// Iterate deeper into the object
          }
          coordinates[i] = itemClone;
        }
        geom.type = gtype;
        geom.coordinates = [Number(coordinates[1]), Number(coordinates[0])];
      }

      // Geometry parameter specified as: {Point: [{coordinates: [lat, lng]}]}
      else if (Array.isArray(val) && val[0].constructor.name === 'Object' && Object.keys(val[0])[0] === 'coordinates'){
        geom.type = gtype;
        geom.coordinates = [Number(item.coordinates[(val[0].coordinates).indexOf('lng')]), Number(item.coordinates[(val[0].coordinates).indexOf('lat')])];
      }
    }

    if(params.doThrows && params.doThrows.invalidGeometry && !GeoJSON.isGeometryValid(geom)){
      throw new InvalidGeometryError(item, params);
    }

    return geom;
  }
764512
function ( buffers, geoInfo, facePositionIndexes, materialIndex, faceNormals, faceColors, faceUVs, faceWeights, faceWeightIndices, faceLength ) {

			for ( var i = 2; i < faceLength; i ++ ) {

				buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ 0 ] ] );
				buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ 1 ] ] );
				buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ 2 ] ] );

				buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ ( i - 1 ) * 3 ] ] );
				buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ ( i - 1 ) * 3 + 1 ] ] );
				buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ ( i - 1 ) * 3 + 2 ] ] );

				buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i * 3 ] ] );
				buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i * 3 + 1 ] ] );
				buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i * 3 + 2 ] ] );

				if ( geoInfo.skeleton ) {

					buffers.vertexWeights.push( faceWeights[ 0 ] );
					buffers.vertexWeights.push( faceWeights[ 1 ] );
					buffers.vertexWeights.push( faceWeights[ 2 ] );
					buffers.vertexWeights.push( faceWeights[ 3 ] );

					buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 ] );
					buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 + 1 ] );
					buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 + 2 ] );
					buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 + 3 ] );

					buffers.vertexWeights.push( faceWeights[ i * 4 ] );
					buffers.vertexWeights.push( faceWeights[ i * 4 + 1 ] );
					buffers.vertexWeights.push( faceWeights[ i * 4 + 2 ] );
					buffers.vertexWeights.push( faceWeights[ i * 4 + 3 ] );

					buffers.weightsIndices.push( faceWeightIndices[ 0 ] );
					buffers.weightsIndices.push( faceWeightIndices[ 1 ] );
					buffers.weightsIndices.push( faceWeightIndices[ 2 ] );
					buffers.weightsIndices.push( faceWeightIndices[ 3 ] );

					buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 ] );
					buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 + 1 ] );
					buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 + 2 ] );
					buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 + 3 ] );

					buffers.weightsIndices.push( faceWeightIndices[ i * 4 ] );
					buffers.weightsIndices.push( faceWeightIndices[ i * 4 + 1 ] );
					buffers.weightsIndices.push( faceWeightIndices[ i * 4 + 2 ] );
					buffers.weightsIndices.push( faceWeightIndices[ i * 4 + 3 ] );

				}

				if ( geoInfo.color ) {

					buffers.colors.push( faceColors[ 0 ] );
					buffers.colors.push( faceColors[ 1 ] );
					buffers.colors.push( faceColors[ 2 ] );

					buffers.colors.push( faceColors[ ( i - 1 ) * 3 ] );
					buffers.colors.push( faceColors[ ( i - 1 ) * 3 + 1 ] );
					buffers.colors.push( faceColors[ ( i - 1 ) * 3 + 2 ] );

					buffers.colors.push( faceColors[ i * 3 ] );
					buffers.colors.push( faceColors[ i * 3 + 1 ] );
					buffers.colors.push( faceColors[ i * 3 + 2 ] );

				}

				if ( geoInfo.material && geoInfo.material.mappingType !== 'AllSame' ) {

					buffers.materialIndex.push( materialIndex );
					buffers.materialIndex.push( materialIndex );
					buffers.materialIndex.push( materialIndex );

				}

				if ( geoInfo.normal ) {

					buffers.normal.push( faceNormals[ 0 ] );
					buffers.normal.push( faceNormals[ 1 ] );
					buffers.normal.push( faceNormals[ 2 ] );

					buffers.normal.push( faceNormals[ ( i - 1 ) * 3 ] );
					buffers.normal.push( faceNormals[ ( i - 1 ) * 3 + 1 ] );
					buffers.normal.push( faceNormals[ ( i - 1 ) * 3 + 2 ] );

					buffers.normal.push( faceNormals[ i * 3 ] );
					buffers.normal.push( faceNormals[ i * 3 + 1 ] );
					buffers.normal.push( faceNormals[ i * 3 + 2 ] );

				}

				if ( geoInfo.uv ) {

					geoInfo.uv.forEach( function ( uv, j ) {

						if ( buffers.uvs[ j ] === undefined ) buffers.uvs[ j ] = [];

						buffers.uvs[ j ].push( faceUVs[ j ][ 0 ] );
						buffers.uvs[ j ].push( faceUVs[ j ][ 1 ] );

						buffers.uvs[ j ].push( faceUVs[ j ][ ( i - 1 ) * 2 ] );
						buffers.uvs[ j ].push( faceUVs[ j ][ ( i - 1 ) * 2 + 1 ] );

						buffers.uvs[ j ].push( faceUVs[ j ][ i * 2 ] );
						buffers.uvs[ j ].push( faceUVs[ j ][ i * 2 + 1 ] );

					} );

				}

			}

		}
452303
def _build_from_geojson(self, src):
        
        geojson = json.loads(self.read(src))
        idx = index.Index()
        data_store = {}
        for i, feature in enumerate(geojson['features']):
            feature = self._build_obj(feature)
            idx.insert(i, feature['geometry'].bounds)
            data_store[i] = feature
        return data_store, idx
1120982
function polygonIntersectLine(x, y, basePoints, centerX, centerY, width, height, padding) {
  var intersections = [];
  var intersection;
  var transformedPoints = new Array(basePoints.length);
  var doTransform = true;

  if (width == null) {
    doTransform = false;
  }

  var points;

  if (doTransform) {
    for (var i = 0; i < transformedPoints.length / 2; i++) {
      transformedPoints[i * 2] = basePoints[i * 2] * width + centerX;
      transformedPoints[i * 2 + 1] = basePoints[i * 2 + 1] * height + centerY;
    }

    if (padding > 0) {
      var expandedLineSet = expandPolygon(transformedPoints, -padding);
      points = joinLines(expandedLineSet);
    } else {
      points = transformedPoints;
    }
  } else {
    points = basePoints;
  }

  var currentX, currentY, nextX, nextY;

  for (var _i2 = 0; _i2 < points.length / 2; _i2++) {
    currentX = points[_i2 * 2];
    currentY = points[_i2 * 2 + 1];

    if (_i2 < points.length / 2 - 1) {
      nextX = points[(_i2 + 1) * 2];
      nextY = points[(_i2 + 1) * 2 + 1];
    } else {
      nextX = points[0];
      nextY = points[1];
    }

    intersection = finiteLinesIntersect(x, y, centerX, centerY, currentX, currentY, nextX, nextY);

    if (intersection.length !== 0) {
      intersections.push(intersection[0], intersection[1]);
    }
  }

  return intersections;
}
155626
function Polygon(polygon) {
        crs(polygon);
        bbox(polygon);
        if (!requiredProperty(polygon, 'coordinates', 'array')) {
            if (!positionArray(polygon.coordinates, 'LinearRing', 2)) {
                rightHandRule(polygon, errors);
            }
        }
    }
697495
def probably_geojson(input):
    ''''''
    valid = False
    if not isinstance(input, dict):
        try:
            input = json.loads(input)
        except ValueError:
            return None
    typename = input.get('type', None)
    supported_types = set([
        'Point', 'LineString', 'Polygon', 'MultiPoint', 'MultiLineString',
        'MultiPolygon', 'GeometryCollection', 'Feature', 'FeatureCollection'
    ])
    valid = typename in supported_types
    return input if valid else None
139749
def normalize_feature_objects(feature_objs):
    """"""
    for obj in feature_objs:
        if hasattr(obj, "__geo_interface__") and \
           'type' in obj.__geo_interface__.keys() and \
           obj.__geo_interface__['type'] == 'Feature':
            yield obj.__geo_interface__
        elif isinstance(obj, dict) and 'type' in obj and \
                obj['type'] == 'Feature':
            yield obj
        else:
            raise ValueError("Did not recognize object {0}"
                             "as GeoJSON Feature".format(obj))
1124962
public static void toGeojsonGeometry(Geometry geom, StringBuilder sb) {
        if (geom instanceof Point) {
            toGeojsonPoint((Point) geom, sb);
        } else if (geom instanceof LineString) {
            toGeojsonLineString((LineString) geom, sb);
        } else if (geom instanceof Polygon) {
            toGeojsonPolygon((Polygon) geom, sb);
        } else if (geom instanceof MultiPoint) {
            toGeojsonMultiPoint((MultiPoint) geom, sb);
        } else if (geom instanceof MultiLineString) {
            toGeojsonMultiLineString((MultiLineString) geom, sb);
        } else if (geom instanceof MultiPolygon) {
            toGeojsonMultiPolygon((MultiPolygon) geom, sb);
        } else {
            toGeojsonGeometryCollection((GeometryCollection) geom, sb);
        }
    }
816731
def contourf_to_geojson_overlap(contourf, geojson_filepath=None, min_angle_deg=None,
                                ndigits=5, unit='', stroke_width=1, fill_opacity=.9,
                                geojson_properties=None, strdump=False, serialize=True):
    """"""
    polygon_features = []
    contourf_idx = 0
    for collection in contourf.collections:
        color = collection.get_facecolor()
        for path in collection.get_paths():
            for coord in path.to_polygons():
                if min_angle_deg:
                    coord = keep_high_angle(coord, min_angle_deg)
                coord = np.around(coord, ndigits) if ndigits else coord
                polygon = Polygon(coordinates=[coord.tolist()])
                fcolor = rgb2hex(color[0])
                properties = set_contourf_properties(stroke_width, fcolor, fill_opacity, contourf.levels, contourf_idx, unit)
                if geojson_properties:
                    properties.update(geojson_properties)
                feature = Feature(geometry=polygon, properties=properties)
                polygon_features.append(feature)
        contourf_idx += 1
    feature_collection = FeatureCollection(polygon_features)
    return _render_feature_collection(feature_collection, geojson_filepath, strdump, serialize)
454449
def polygon(surf, points, color):
    """"""

    gfxdraw.aapolygon(surf, points, color)
    gfxdraw.filled_polygon(surf, points, color)

    x = min([x for (x, y) in points])
    y = min([y for (x, y) in points])
    xm = max([x for (x, y) in points])
    ym = max([y for (x, y) in points])

    return pygame.Rect(x, y, xm - x, ym - y)
1228288
def pointsToVoronoiGridShapefile(lat, lon, vor_shp_path, extent=None):
    
    voronoi_centroids = _get_voronoi_centroid_array(lat, lon, extent)

    # set-up output polygon shp
    log("Creating output polygon shp {0}"
        .format(os.path.basename(vor_shp_path)))
    if os.path.exists(vor_shp_path):
        os.remove(vor_shp_path)
    drv = ogr.GetDriverByName('ESRI Shapefile')
    outShp = drv.CreateDataSource(vor_shp_path)
    osr_geographic_proj = osr.SpatialReference()
    osr_geographic_proj.ImportFromEPSG(4326)
    layer = outShp.CreateLayer('', osr_geographic_proj, ogr.wkbPolygon)
    layer.CreateField(ogr.FieldDefn('GRID_LAT', ogr.OFTReal))
    layer.CreateField(ogr.FieldDefn('GRID_LON', ogr.OFTReal))
    layerDefn = layer.GetLayerDefn()

    # find nodes surrounding polygon centroid
    # sort nodes in counterclockwise order
    # create polygon perimeter through nodes
    log("Building Voronoi polygons...")
    # compute voronoi
    voronoi_manager = Voronoi(voronoi_centroids)
    voronoi_vertices = voronoi_manager.vertices
    voronoi_regions = voronoi_manager.regions
    for point_id, region_index in enumerate(voronoi_manager.point_region):
        vert_index_list = np.array(voronoi_regions[region_index])
        voronoi_centroid = voronoi_centroids[point_id]
        voronoi_poly_points = _get_voronoi_poly_points(vert_index_list,
                                                       voronoi_vertices,
                                                       voronoi_centroid)
        if len(voronoi_poly_points) == 4:
            poly = ogr.Geometry(ogr.wkbPolygon)
            ring = ogr.Geometry(ogr.wkbLinearRing)
            for node in voronoi_poly_points:
                ring.AddPoint(node[0], node[1])

            # grab first node to close ring
            ring.AddPoint(voronoi_poly_points[0][0], voronoi_poly_points[0][1])

            poly.AddGeometry(ring)
            feat = ogr.Feature(layerDefn)
            feat.SetField('GRID_LON', float(voronoi_centroid[0]))
            feat.SetField('GRID_LAT', float(voronoi_centroid[1]))
            feat.SetGeometry(poly)
            layer.CreateFeature(feat)
820980
function (points) {
    return new BVG('polyline', points.constructor.name === 'Object' ? points : {
      points: points
    }, function (tag, data) {
      tag.setAttribute('points', data.points.join(' '));
    });
  }