[GIS] Creating point in shapefile from latitude/longitude using GeoTools

geotoolsjava

I m new to geotools and i find bit difficult to plot a point using the latitude and longitude values. can any one heple me out to solve my problem.

GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory():
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE); 
Point point = geometryFactory.createPoint(new Coordinate(longitude, latitude));
featureBuilder.add(point);

but this code is not working properly. could any one explain why..?

Best Answer

In your code, you miss to define a feature type: In GeoTools (and not only), you will first need to define the structure of your data, ie the Feature type (~ schema). For this you have to use SimpleFeatureTypeBuilder that will help to build the feature type, afterwhat you will be able to construct properly the SimpleFeatureBuilder based on the featuretype you defined before (the TYPE argument in your code)

Create the Simple Feature Type (structure of your data):

SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();

//set the name
b.setName( "MyFeatureType" );

//add a geometry property
b.setCRS( DefaultGeographicCRS.WGS84 ); // set crs first
b.add( "location", Point.class ); // then add geometry

//build the type
final SimpleFeatureType TYPE = b.buildFeatureType();

Create the feature(s) using the feature type previously defined

SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE);
GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
Point point = geometryFactory.createPoint(new Coordinate(longitude, latitude));
featureBuilder.add(point);
SimpleFeature feature = featureBuilder.buildFeature( "fid.1" ); // build the 1st feature

Next step, you can create a feature collection, using the feature(s) you defined before:

DefaultFeatureCollection featureCollection = new DefaultFeatureCollection("internal",TYPE);
featureCollection.add(feature); //Add feature 1
// Add feature 2, 3, etc

I recommend you to follow examples from http://docs.geotools.org/latest/userguide/library/main This will also help to understand how geospatial data is structured in Geotools

For the plotting part, i suggest you to familiarize with the geotools rendering module: http://docs.geotools.org/latest/userguide/library/render/map.html.

Related Question