2013-09-13 4 views
2

Я создаю простую программу, которая считывает значения из файла csv и создает файл shp на основе этих значений. Это модификация скольжения this exampleПочему этот фрагмент GeoTool не создает видимый шейп-файл?

Файл формы, кажется, создан, но когда я просматриваю шейп-файл with a another snippet, я ничего не вижу. Другие примеры shapefiles, которые я могу просмотреть с помощью этой программы.

Что мне недостает в моем коде?

Мои данные:

LAT1, LON1, LAT2, LON2, LAT3, LON3, LAT3, LON3, CITY, NUMBER 
10, 10, 20, 20, 30, 30, 10, 10, Trento, 140 

Мой код:

public class ShapeReaderWriter { 

    public static void main(String[] args) throws Exception { 

     //read the xml file 
     File file = FileUtils.getFile("D:\\workspaces\\Routeguard\\Xml2Shape\\src\\com\\meteogroup\\conversion\\locations.csv"); 

     List<String> lines = FileUtils.readLines(file, "utf-8"); 

     final SimpleFeatureType TYPE = createFeatureType(); 

     List<SimpleFeature> features = new ArrayList<SimpleFeature>();   

     GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null); 
     SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE); 

     int i = 0; 
     for(String line : lines){ 
      if (i > 0 && line.trim().length() > 0) { // skip blank lines + header 
       String tokens[] = line.split("\\,"); 

       Coordinate[] coordinates = createPolygonDescription(tokens, 8); //the number of values the polygon has 

       String name = tokens[8].trim(); 
       int number = Integer.parseInt(tokens[9].trim()); 

       /* Longitude (= x coord) first ! */ 
       Polygon polygon = geometryFactory.createPolygon(coordinates); 
       featureBuilder.add(polygon); 
       featureBuilder.add(name); 
       featureBuilder.add(number); 
       SimpleFeature feature = featureBuilder.buildFeature(null); 
       features.add(feature); 
      } 
      i++; 
     } 

     /* 
     * Get an output file name and create the new shapefile 
     */ 
     File newFile = getNewShapeFile(file); 

     ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory(); 

     Map<String, Serializable> params = new HashMap<String, Serializable>(); 
     params.put("url", newFile.toURI().toURL()); 
     params.put("create spatial index", Boolean.TRUE); 

     ShapefileDataStore newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params); 
     newDataStore.createSchema(TYPE); 

     /* 
     * You can comment out this line if you are using the createFeatureType method (at end of 
     * class file) rather than DataUtilities.createType 
     */ 
     //newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84); 

     /* 
     * Write the features to the shapefile 
     */ 
     Transaction transaction = new DefaultTransaction("create"); 

     String typeName = newDataStore.getTypeNames()[0]; 
     SimpleFeatureSource featureSource = newDataStore.getFeatureSource(typeName); 

     if (featureSource instanceof SimpleFeatureStore) { 
      SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource; 

      /* 
      * SimpleFeatureStore has a method to add features from a 
      * SimpleFeatureCollection object, so we use the ListFeatureCollection 
      * class to wrap our list of features. 
      */ 
      SimpleFeatureCollection collection = new ListFeatureCollection(TYPE, features); 
      featureStore.setTransaction(transaction); 
      try { 
       featureStore.addFeatures(collection); 
       transaction.commit(); 

      } catch (Exception problem) { 
       problem.printStackTrace(); 
       transaction.rollback(); 

      } finally { 
       transaction.close(); 
      } 
      System.exit(0); // success! 
     } else { 
      System.out.println(typeName + " does not support read/write access"); 
      System.exit(1); 
     } 

    } 

    private static Coordinate[] createPolygonDescription(String[] tokens, int max) { 
     Coordinate[] coords = new Coordinate[max/2]; 
     int j = 0; 
     for(int i = 0 ; i < max; i = i+2){ 
      Coordinate c = new Coordinate(Double.parseDouble(tokens[i + 1]), Double.parseDouble(tokens[i])); // seems weird but isn't -> lon is the x value, lat is the y 
      coords[j] = c; 
      j++; 
     } 
     return coords; 
    } 

    private static SimpleFeatureType createFeatureType() { 

     SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder(); 
     builder.setName("Location"); 
     builder.setCRS(DefaultGeographicCRS.WGS84); // <- Coordinate reference system 

     // add attributes in order 
     builder.add("Polygon", Polygon.class); 
     builder.length(15).add("Name", String.class); // <- 15 chars width for name field 
     builder.add("Number", Integer.class); 

     // build the type 
     final SimpleFeatureType LOCATION = builder.buildFeatureType(); 

     return LOCATION; 
    } 

    private static File getNewShapeFile(File csvFile) { 
     String path = csvFile.getAbsolutePath(); 
     String newPath = path.substring(0, path.length() - 4) + ".shp"; 

     JFileChooser chooser = new JFileChooser("shp"); 
     chooser.setDialogTitle("Save shapefile"); 
     chooser.setSelectedFile(new File(newPath)); 

     int returnVal = chooser.showSaveDialog(null); 

     if (returnVal != JFileChooser.APPROVE_OPTION) { 
      // the user cancelled the dialog 
      System.exit(0); 
     } 

     File newFile = chooser.getSelectedFile(); 
     if (newFile.equals(csvFile)) { 
      System.out.println("Error: cannot replace " + csvFile); 
      System.exit(0); 
     } 

     return newFile; 
    } 

} 

И мой зритель:

общественного класса Quickstart {

/** 
* GeoTools Quickstart demo application. Prompts the user for a shapefile and displays its 
* contents on the screen in a map frame 
*/ 
public static void main(String[] args) throws Exception { 
    // display a data store file chooser dialog for shapefiles 
    File file = JFileDataStoreChooser.showOpenFile("shp", null); 
    if (file == null) { 
     return; 
    } 

    FileDataStore store = FileDataStoreFinder.getDataStore(file); 
    SimpleFeatureSource featureSource = store.getFeatureSource(); 

    // Create a map content and add our shapefile to it 
    MapContent map = new MapContent(); 
    map.setTitle("Quickstart"); 

    Style style = SLD.createSimpleStyle(featureSource.getSchema()); 
    Layer layer = new FeatureLayer(featureSource, style); 
    map.addLayer(layer); 

    // Now display the map 
    JMapFrame.showMap(map); 
} 

}

Благодарим вас и проголосуйте за длинный фрагмент!

+0

Вы можете открыть файл формы с помощью ГИС? Это будет сужаться там, где проблема. –

+0

Если я загружу файл по адресу http://lsi.iiit.ac.in/lsi/shpviewer/, я ничего не вижу, примеры файлов из других источников действительно показывают .. – jorrebor

+0

такая же проблема здесь :( – Maurix

ответ

0

Стабильная ветвь работ, как ожидается, для всех, кто ищет решения этого является то, что я узнал до сих пор:

  • 10-ПАНОРАМА: не работает
  • 11-ПАНОРАМА: не работает
  • 2.7.5: работа

Не совсем ответ, который вы можете искать, но для меня это уже не зацикливаться!

+0

ah great, я в итоге взял другое направление, но попробуем это! – jorrebor

+0

Это все еще так? – Boj

4

Похоже, что geotools жестко кодирует имя геометрии как «the_geom» внутри.

я получаю ту же ошибку, и это фиксируется, заменив строку:

builder.add("Polygon", Polygon.class); 

с этим:

builder.add("the_geom", Polygon.class); 
+0

Спецификация шейп-файла требует, чтобы столбец геометрии назывался «the_geom», поэтому мы исправили старый код, который разрешил что-либо. –