GeoJson化


前記事の続き

MongoDBを試す

結局
Can’t extract geo keys from object, malformed geometry?
と言うエラー原因の深追いは諦めて、速度回りの確認に移行した。

GeoJson化があまりに適当だったので修正

var type = geom.STGeometryType().Value;

StringBuilder sb = new StringBuilder();
sb.AppendFormat("{{\"type\": \"{0}\", \"coordinates\": ", type);


if (type == "Point")
{
  sb.AppendFormat("[{0},{1}]", geom.STX.Value, geom.STY.Value);
}
else if (type == "MultiLineString" || type == "LineString")
{
  if (type == "MultiLineString")
    sb.Append("[");

  for (int i = 0; i < geom.STNumGeometries().Value; i++)
  {
    sb.Append("[");
    var ngeom = geom.STGeometryN(i + 1);

    SqlGeometry pt = ngeom.STPointN(1);
    sb.AppendFormat("[{0},{1}]", pt.STX.Value, pt.STY.Value);
    for (int j = 1; j < ngeom.STNumPoints().Value; j++)
    {
      pt = ngeom.STPointN(j + 1);
      sb.AppendFormat(",[{0},{1}]", pt.STX.Value, pt.STY.Value);
    }//end point loop

    sb.Append("]");
  }//end loop

  if (type == "MultiLineString")
    sb.Append("]");
}
else if (type == "MultiPolygon" || type == "Polygon")
{
  if (type == "MultiPolygon")
    sb.Append("[");

  for (int i = 0; i < geom.STNumGeometries().Value; i++)
  {
    var ngeom = geom.STGeometryN(i + 1);

    if (i != 0)
      sb.Append(",");

    sb.Append("[");

    List<SqlGeometry> lstGeom = new List<SqlGeometry>();
    lstGeom.Add(ngeom.STExteriorRing());
    for (int ir = 0; ir < ngeom.STNumInteriorRing().Value; ir++)
    {
      var ring = ngeom.STInteriorRingN(ir + 1);
      lstGeom.Add(ring);
    }

    bool isFirstTime = true;
    foreach (var ring in lstGeom)
    {
      if (isFirstTime)
        isFirstTime = false;
      else
        sb.Append(",");

      sb.Append("[");
      SqlGeometry pt = ring.STPointN(1);
      sb.AppendFormat("[{0},{1}]", pt.STX.Value, pt.STY.Value);
      for (int j = 1; j < ring.STNumPoints().Value; j++)
      {
        pt = ring.STPointN(j + 1);
        sb.AppendFormat(",[{0},{1}]", pt.STX.Value, pt.STY.Value);
      }//end point loop
      if (pt.STX.Value != ring.STPointN(1).STX.Value ||
          pt.STY.Value != ring.STPointN(1).STY.Value)
      {
        sb.AppendFormat(",[{0},{1}]", ring.STPointN(1).STX.Value, ring.STPointN(1).STY.Value);
      }
      sb.Append("]");
    }

    sb.Append("]");
  }//end geom loop

  if (type == "MultiPolygon")
    sb.Append("]");
}

else
{
  throw new Exception("想定外の図形");
}
sb.Append("}");
カテゴリー: 開発 タグ: パーマリンク