geotools
Geo-related tools PHP 5.4+ library built atop Geocoder and React libraries
thephpleague/geotools · GitHub geotools - geo-related tools php 5.4+ library built atop geocoder and react libraries
I have some grid data (2d array) that has some geospatial metadata associated with it. The bounds are in a jts polygon with WSG84 lon lat coordinates. The polygon is a rectangle, but is not axis aligned (not a bounding box).
I am trying to create a geotools CoordinateReferenceSystem object that describes this coverage. I want to use the CRS to reproject the coverage, but I also need to use the CRS as-is so skipping the CRS creation step is no good.
Boiled down:
How do you go from a WSG84 polygon, dx, dy, nx, ny to a CoordinateReferenceSystem object that describes the grid using geotools?
Thanks in advance for the help
Source: (StackOverflow)
Does anyone know of a way, in Java, to convert an earth surface position from lat, lon to UTM (say in WGS84)? I'm currently looking at Geotools but unfortunately the solution is not obvious.
Source: (StackOverflow)
I am using geotools to extract data from shapefiles and store them into mysql. My application works all the time but I get this lock every so often which i cannot understand why, as it still works
[root@website-qc filespool]# /usr/bin/java -jar /opt/mcmap/library/Application/geotools/mcgeotools.jar -t publisher -i 1/194/Namibia_SCLB12.shp -rid 12 -s
app get cmd option cast to int: 12
app passing region id to runconvert: 12
runconvert rid passed: 12
Jul 9, 2012 4:23:48 PM org.geotools.data.db2.DB2DataStoreFactory isAvailable
INFO: DB2 driver found: true
Database connection acquired
Coordinates length: 5390
Coordinates length: 5358
Coordinates length: 9932
Jul 9, 2012 4:28:14 PM org.geotools.data.shapefile.ShpFiles logCurrentLockers
SEVERE: The following locker still has a lock� read on file:/opt/mcmap/public/filespool/1/194/Namibia_SCLB12.prj by org.geotools.data.shapefile.prj.PrjFileReader
it was created with the following stack trace
org.geotools.data.shapefile.ShpFilesLocker$Trace: Locking file:/opt/mcmap/public/filespool/1/194/Namibia_SCLB12.prj for read by org.geotools.data.shapefile.prj.PrjFileReader in thread main
at org.geotools.data.shapefile.ShpFilesLocker.setTraceException(ShpFilesLocker.java:72)
at org.geotools.data.shapefile.ShpFilesLocker.<init>(ShpFilesLocker.java:36)
at org.geotools.data.shapefile.ShpFiles.acquireRead(ShpFiles.java:365)
at org.geotools.data.shapefile.ShpFiles.getReadChannel(ShpFiles.java:813)
at org.geotools.data.shapefile.prj.PrjFileReader.<init>(PrjFileReader.java:66)
at com.domain.mcgeotools.convert.Converter.getCoordinateSystem(Converter.java:521)
at com.domain.mcgeotools.convert.Converter.runConvert(Converter.java:106)
at com.domain.mcgeotools.App.main(App.java:158)
Coordinates length: 5741
Coordinates length: 5374
Coordinates length: 4193
Coordinates length: 14161
Coordinates length: 5375
Coordinates length: 4212
below is my app code
package com.domain.mcgeotools.convert;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.File;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.util.Properties;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.sql.*;
import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFinder;
import org.geotools.data.FeatureSource;
import org.geotools.data.shapefile.*;
import org.geotools.data.shapefile.prj.PrjFileReader;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.geotools.feature.simple.SimpleFeatureImpl;
import org.opengis.feature.Property;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
public class Converter {
protected String filePath = null;
private Properties configFile = null;
private String[] acceptedCoordinateSytems = {
"Lat Long for MAPINFO type 0 Datum",
"GCS_WGS_1984"
};
private HashMap sqlStatements = new HashMap();
private int sqlCounter = 0;
public Converter() throws IOException {
/**
* We load the configuration details from the properties file and use the config. The config property
* item stores things such as database connection details etc.
*/
this.configFile = new Properties();
this.configFile.load(this.getClass().getClassLoader().getResourceAsStream("mcgeotools-config.properties"));
}
protected void setFilePath(String filePath) {
this.filePath = filePath;
}
protected String getFilePath() {
return this.filePath;
}
/**
* Converts the passed shape files and place the data into the RDBMS
*
* @param filePath
* @param verbose
* @param shrink
* @return
* @throws Exception
*/
public int runConvert(String filePath, int regionId, boolean verbose, boolean shrink, String type) throws Exception {
System.out.println("runconvert rid passed: " + regionId);
ShapeFile shapeFile = new ShapeFile();
if (!shapeFile.isShapeFile(filePath)) {
System.out.println(filePath);
throw new Exception("Not a shape file");
}
//we get the coordinate type from the shape file
String coordinateSystem = null;
try {
coordinateSystem = this.getCoordinateSystem(filePath);
if (verbose) {
//Print to console.
System.out.println("Coordinate System: " + coordinateSystem + " for " + filePath);
}
} catch (Exception cse) {
Logger.getLogger(Converter.class.getName()).log(Level.SEVERE, null, cse);
}
boolean acceptedSystem = false;
for (int i = 0; i < this.acceptedCoordinateSytems.length; i++) {
if (this.acceptedCoordinateSytems[i].equalsIgnoreCase(coordinateSystem)) {
acceptedSystem = true;
}
}
if (!acceptedSystem) {
throw new Exception("Not an excepted Coordinate System.");
}
//we now load the shapefile into the application
File file = new File(filePath);
if (file == null) {
throw new Exception("Failed to open " + filePath);
}
Map connect = new HashMap();
connect.put("url", file.toURI().toURL());
DataStore dataStore = DataStoreFinder.getDataStore(connect);
String[] typeNames = dataStore.getTypeNames();
String typeName = typeNames[0];
FeatureSource featureSource = dataStore.getFeatureSource(typeName);
FeatureCollection collection = featureSource.getFeatures();
FeatureIterator iterator = collection.features();
//database connection
Connection dbConn = null;
int surveyDbId = 0;
String localhostname = java.net.InetAddress.getLocalHost().getHostName();
try {
String dbUser = "", dbPwd = "", dbUrl = "";
dbUser = this.configFile.getProperty("DB_USER");
dbPwd = this.configFile.getProperty("DB_PASSWORD");
dbUrl = "jdbc:" + this.configFile.getProperty("DB_CONNSTR");
dbUrl = "jdbc:mysql://"+ localhostname +"/mcdatabase";
// If publishing overite connection strings
if(type.equals("publish")){
dbUser = this.configFile.getProperty("DB_PB_USER");
dbPwd = this.configFile.getProperty("DB_PB_PASSWORD");
dbUrl = "jdbc:" + this.configFile.getProperty("DB_PB_CONNSTR");
}
Class.forName("com.mysql.jdbc.Driver").newInstance();
dbConn = DriverManager.getConnection(dbUrl, dbUser, dbPwd);
System.out.println("Database connection acquired");
//switch off auto commits so that we run this as one transaction.
dbConn.setAutoCommit(false);
this.sqlStatements.put(this.sqlCounter, "START TRANSACTION");
this.sqlCounter++;
PreparedStatement surveyStmt = null;
ResultSet rs = null;
if(type.equals("convert")){
//insert data in to the survey table and get the last row ID.
surveyStmt = dbConn.prepareStatement("INSERT INTO surveys (name, guid, date_added, region_id, shrink) VALUES( ?, md5(now()), now(), ?, ? )");
surveyStmt.setString(1, typeName.replaceAll("%20", " "));
surveyStmt.setInt(2, regionId);
surveyStmt.setBoolean(3, shrink);
surveyStmt.executeUpdate();
rs = surveyStmt.getGeneratedKeys();
rs.first();
surveyDbId = rs.getInt(1);
this.sqlStatements.put(this.sqlCounter, "INSERT INTO surveys (name, guid, date_added, region_id, shrink) VALUES( '"+ typeName.replaceAll("%20", " ") +"', md5(now()), now(), "+ regionId +", "+ shrink +")");
}else if(type.equals("publish")){
//insert data in to the survey table and get the last row ID.
surveyStmt = dbConn.prepareStatement("INSERT INTO surveys (name, guid, published, date_added, region_id, shrink) VALUES( ?, md5(now()), 1, now(), ?, ? )");
surveyStmt.setString(1, typeName.replaceAll("%20", " "));
surveyStmt.setInt(2, regionId);
surveyStmt.setBoolean(3, shrink);
surveyStmt.executeUpdate();
rs = surveyStmt.getGeneratedKeys();
rs.first();
surveyDbId = rs.getInt(1);
this.sqlStatements.put(this.sqlCounter, "INSERT INTO surveys (name, guid, published, date_added, region_id, shrink) VALUES( '"+ typeName.replaceAll("%20", " ") +"', md5(now()), 1, now(), "+ regionId +", "+ shrink +")");
}
this.sqlCounter++;
rs.close();
surveyStmt.close();
//Total lat/long values to work center point.
double totalLat = 0.0;
double totalLong = 0.0;
int totalLongLats = 0;
while (iterator.hasNext()) {
SimpleFeatureImpl feature = (SimpleFeatureImpl) iterator.next();
Geometry sourceGeometry = (Geometry) feature.getDefaultGeometry();
//we now need to enter a link between the survey and the line data.
PreparedStatement lineStmt = null;
String lineStmtSQL = "INSERT INTO `lines` (guid, date_added, survey_id) VALUES (md5(now()), now(), ?)";
lineStmt = dbConn.prepareCall(lineStmtSQL);
lineStmt.setInt(1, surveyDbId);
lineStmt.executeUpdate();
ResultSet lineRS = lineStmt.getGeneratedKeys();
lineRS.first();
int lineDbId = lineRS.getInt(1);
this.sqlStatements.put(this.sqlCounter, "INSERT INTO `lines` (guid, date_added, survey_id) VALUES (md5(now()), now(), " +
surveyDbId +")");
this.sqlCounter++;
lineRS.close();
lineStmt.close();
//we now look for the properties of the line that we are about to process.
Collection<Property> coll = feature.getProperties();
Iterator colIterator = coll.iterator();
//we now look at inserting the line properties into the database.
PreparedStatement linePropStmt = null;
String linePropSQL = "INSERT INTO line_properties(`key`, `value`, `line_id`) VALUES(?, ?, ?)";
linePropStmt = dbConn.prepareStatement(linePropSQL);
while (colIterator.hasNext()) {
Property geoProp = (Property) colIterator.next();
if (verbose) {
System.out.println("prop name: " + geoProp.getName() + " Value: " + geoProp.getValue());
}
if (geoProp.getValue() != null && !geoProp.getName().toString().equals("the_geom")) {
//we then prepare the statment and execute for each property.
linePropStmt.setString(1, geoProp.getName().toString());
linePropStmt.setString(2, geoProp.getValue().toString());
linePropStmt.setInt(3, lineDbId);
linePropStmt.executeUpdate();
//add to sql command hashmap
this.sqlStatements.put(this.sqlCounter, "INSERT INTO line_properties(`key`, `value`, `line_id`) VALUES('" +
geoProp.getName().toString()+"', '"+
geoProp.getValue().toString()+"', "+lineDbId+")");
this.sqlCounter++;
}
}
//close the prepared statement now that we've finished with it.
linePropStmt.close();
//finally we populate the line coordinates into the database.
Coordinate[] coordinates = sourceGeometry.getCoordinates();
String lineName = feature.getID();
if (verbose) {
System.out.println(lineName);
}
PreparedStatement coordStmt = null;
String coordSQL = "INSERT INTO coordinates(`x`, `y`, line_id, sequence) VALUES(?, ?, ?, ?)";
coordStmt = dbConn.prepareStatement(coordSQL);
PreparedStatement lineStringStmt = null;
String longLatSQL = "UPDATE `lines` SET longlat_string = ? WHERE line_id = ?";
lineStringStmt = dbConn.prepareStatement(longLatSQL);
/**
* Used to build a full long lat string for fast lookups
* when being used in KML/Google Maps
*/
String longLatString = "";
boolean first = true;
int shotCount = 0;
System.out.println("Coordinates length: "+ coordinates.length);
for (int i = 0; i < coordinates.length; i++) {
if (verbose) {
System.out.println("x: " + coordinates[i].x + " - Y: " + coordinates[i].y);
}
//add to the long lat counter to find center point
totalLat += coordinates[i].x;
totalLong += coordinates[i].y;
totalLongLats++;
coordStmt.setString(1, Double.toString(coordinates[i].x));
coordStmt.setString(2, Double.toString(coordinates[i].y));
coordStmt.setInt(3, lineDbId);
coordStmt.setInt(4, i);
coordStmt.executeUpdate();
this.sqlStatements.put(this.sqlCounter, "INSERT INTO coordinates(`x`, `y`, line_id, sequence) VALUES('"+
Double.toString(coordinates[i].x) +"', '"+
Double.toString(coordinates[i].y) +"', "+lineDbId+", "+i+")");
this.sqlCounter++;
//now we build/update a string for the full coordinates.
if (first) {
longLatString = Double.toString(coordinates[i].x) + "," + Double.toString(coordinates[i].y);
first = false;
} else {
// Not implemented function fully, to strip long lats to start and end points only
if(shrink){
if(i == (coordinates.length -1)){
longLatString += ",0 " + Double.toString(coordinates[i].x) + "," + Double.toString(coordinates[i].y);
}
}else{
/* // testing this if
if( coordinates.length < 10 && shotCount == 2 ){
longLatString += ",0 " + Double.toString(coordinates[i].x) + "," + Double.toString(coordinates[i].y);
shotCount = 0;
}else */
//if( coordinates.length >= 10 && coordinates.length < 30 && shotCount == 4 ){
if( coordinates.length < 30 && shotCount == 4 ){
longLatString += ",0 " + Double.toString(coordinates[i].x) + "," + Double.toString(coordinates[i].y);
shotCount = 0;
}else if( coordinates.length >= 30 && coordinates.length < 100 && shotCount == 9 ){
longLatString += ",0 " + Double.toString(coordinates[i].x) + "," + Double.toString(coordinates[i].y);
shotCount = 0;
}else if( coordinates.length >= 100 && coordinates.length < 1000 && shotCount == 49 ){
longLatString += ",0 " + Double.toString(coordinates[i].x) + "," + Double.toString(coordinates[i].y);
shotCount = 0;
}else if( coordinates.length >= 1000 && coordinates.length < 10000 && shotCount == 99 ){
longLatString += ",0 " + Double.toString(coordinates[i].x) + "," + Double.toString(coordinates[i].y);
shotCount = 0;
}else if( coordinates.length >= 10000 && shotCount == 199 ){
longLatString += ",0 " + Double.toString(coordinates[i].x) + "," + Double.toString(coordinates[i].y);
shotCount = 0;
}
// Make sure to get last co-ordinate of line
if( i == (coordinates.length-1) ){ // -1 since coutn starts from zero
longLatString += ",0 " + Double.toString(coordinates[i].x) + "," + Double.toString(coordinates[i].y);
System.out.println("Last coordinate stored: " + longLatString);
shotCount = 0;
}
}
}
shotCount ++;
}
/**
* Update the line table to include the precreated line string.
*/
lineStringStmt.setString(1, longLatString);
lineStringStmt.setInt(2, lineDbId);
lineStringStmt.executeUpdate();
this.sqlStatements.put(this.sqlCounter, "UPDATE `lines` SET longlat_string = '"+longLatString+"' WHERE line_id = " + lineDbId);
this.sqlCounter++;
lineStringStmt.close();
coordStmt.close();
}
//finally we update the center point
PreparedStatement centerPointStmt = null;
String centerPointSQL = "UPDATE `surveys` SET center_point = ? WHERE survey_id = ?";
centerPointStmt = dbConn.prepareStatement(centerPointSQL);
double centerLat = totalLat/totalLongLats;
double centerLong = totalLong/totalLongLats;
String centerPoint = Double.toString(centerLat) + ", " + Double.toString(centerLong);
centerPointStmt.setString(1, centerPoint);
centerPointStmt.setInt(2, surveyDbId);
centerPointStmt.executeUpdate();
centerPointStmt.close();
this.sqlStatements.put(this.sqlCounter, "UPDATE `surveys` SET center_point = '"+centerPoint+"' WHERE survey_id = "+surveyDbId);
this.sqlCounter++;
//we now commit the transaction
dbConn.commit();
//now we can close the database connection.
dbConn.close();
this.sqlStatements.put(this.sqlCounter,"COMMIT");
this.sqlCounter++;
BufferedWriter out = new BufferedWriter(new java.io.FileWriter(this.configFile.getProperty("SQL_FILE").toString()));
for(int i = 0; i < this.sqlStatements.size(); i++){
out.write(this.sqlStatements.get(i) + ";" + "\n");
}
//close file connection
out.close();
System.out.println("End transaction");
} catch (Exception ex) {
System.out.println();
System.out.println("Message: "+ex.getMessage());
if(ex.getMessage().trim().contains("Communications link failure")){
System.out.println("Check there is a mysql connection and retry");
System.out.println();
System.exit(0);
}else{
Logger.getLogger(Converter.class.getName()).log(Level.SEVERE, null, ex);
//we've errored so we need to toll back the connection.
dbConn.rollback();
//we now insert a message into the audit log.
String auditSQL = "INSERT INTO auditlog (username, date_added, message, guid, type)" + "VALUES('mcgeotools', now(), ?, md5(now()), ?)";
PreparedStatement auditStmt = dbConn.prepareStatement(auditSQL);
//we want to know which survey failed to import and we need the stacktrace message.
String auditMessage = "Error whilst populating Survey " + typeName + " with error message : " + ex.getMessage();
auditStmt.setString(1, auditMessage);
auditStmt.setString(2, "error"); //error
auditStmt.execute();
dbConn.commit();
}
} finally {
//close the iterator
iterator.close();
//commit any transaction and close the connection to the database if it is open.
if (dbConn != null && !dbConn.isClosed()) {
try {
dbConn.commit();
dbConn.close();
} catch (Exception dbex) {
System.out.println("Communications failure, check there is a connection to mysql");
Logger.getLogger(Converter.class.getName()).log(Level.SEVERE, null, dbex);
}
}
//close file connection
}
return surveyDbId;
}
/**
* Get the coordinate system that is used in the shape file
*
* @param String shpFilePath
* @return String
*/
private String getCoordinateSystem(String shpFilePath) throws MalformedURLException, IOException {
String coordType = null;
ShpFiles shapeFiles = new ShpFiles(shpFilePath);
PrjFileReader fileReader = new PrjFileReader(shapeFiles);
CoordinateReferenceSystem coordSystem = fileReader.getCoodinateSystem();
coordType = coordSystem.getName().toString();
return coordType;
}
}
@Andre
Errors
Feb 22, 2013 12:03:54 PM org.geotools.data.shapefile.ng.files.ShpFiles logCurrentLockers
SEVERE: The following locker still has a lock: read on file:/tmp/24/FozDoAmazonasPhase2.shp by org.geotools.data.shapefile.ng.shp.ShapefileReader
Feb 22, 2013 12:03:54 PM org.geotools.data.shapefile.ng.files.ShpFiles logCurrentLockers
SEVERE: The following locker still has a lock: read on file:/tmp/24/FozDoAmazonasPhase2.shx by org.geotools.data.shapefile.ng.shp.IndexFile
Feb 22, 2013 12:03:54 PM org.geotools.data.shapefile.ng.files.ShpFiles logCurrentLockers
SEVERE: The following locker still has a lock: read on file:/tmp/24/FozDoAmazonasPhase2.dbf by org.geotools.data.shapefile.ng.dbf.DbaseFileReader
Feb 22, 2013 12:04:39 PM com.spectrumasa.mcgeotools.App main
SEVERE: null
java.lang.IllegalArgumentException: Expected requestor org.geotools.data.shapefile.ng.dbf.DbaseFileReader@1966c114 to have locked the url but it does not hold the lock for the URL
at org.geotools.data.shapefile.ng.files.ShpFiles.unlockRead(ShpFiles.java:433)
at org.geotools.data.shapefile.ng.files.FileChannelDecorator.implCloseChannel(FileChannelDecorator.java:149)
at java.nio.channels.spi.AbstractInterruptibleChannel.close(AbstractInterruptibleChannel.java:114)
at org.geotools.data.shapefile.ng.dbf.DbaseFileReader.close(DbaseFileReader.java:279)
at org.geotools.data.shapefile.ng.ShapefileFeatureReader.close(ShapefileFeatureReader.java:248)
at org.geotools.data.store.ContentFeatureCollection$WrappingFeatureIterator.close(ContentFeatureCollection.java:227)
at com.spectrumasa.mcgeotools.convert.Converter.runConvert(Converter.java:487)
at com.spectrumasa.mcgeotools.App.main(App.java:100)
Source: (StackOverflow)
I'm interested in writing a visualization program for the road data in the 2009 Tiger/Line Shapefiles. I'd like to draw the line data to display all the roads for my county.
The ESRI Shapefile or simply a
shapefile is a popular geospatial
vector data format for geographic
information systems software. It is
developed and regulated by ESRI as a
(mostly) open specification for data
interoperability among ESRI and other
software products.1 A "shapefile"
commonly refers to a collection of
files with ".shp", ".shx", ".dbf", and
other extensions on a common prefix
name (e.g., "lakes.*"). The actual
shapefile relates specifically to
files with the ".shp" extension,
however this file alone is incomplete
for distribution, as the other
supporting files are required.
Does anyone know of existing libraries for parsing and reading in the line data for Shapefiles?
Source: (StackOverflow)
I have m2e
installed in Eclipse
and global maven configured in it. Recently I have added two geottools repositories, but Eclipse
does not show them:
Also it is not finding artefacts from it, like gt-shapefile
.
How to force indexing? Rebuild Index
and Update Index
did not help. Removing m2e
plugin folders from .metadata
workspace folder also didn't help.
Source: (StackOverflow)
Looking for a java utility. It is even better if you can tell me how to do it using geotools library.
Source: (StackOverflow)
What is Google map's spatial reference system using when you enter a lat, long into the maps search bar?
I've found hints that it might be WGS84 but after converting to that coordinate system, nothing shows up when i paste the coordinates into the google maps search box.
I am converting from GDA MGA 56.
Sample:
- Input MGA56 coords: 336301, 6253363
- Expected WGS86 coords: -33.8473340793201, 151.230631835944
- I get: 16834916.928327594 -4008321.1020318186
Spatial coord systems:
- EPSG:28356 for MGA56
- EPSG:900913 for WGS86 (google maps)
I am using geotools to do the transform:
CoordinateReferenceSystem crsMga56 = CRS.parseWKT(mga56);
CoordinateReferenceSystem crsGmaps = CRS.parseWKT(gmaps);
Coordinate coordinate = new Coordinate(336301, 6253363);
Point point = new GeometryFactory().createPoint(coordinate);
MathTransform transform = CRS.findMathTransform(crsMga56, crsGmaps);
Geometry geometry = JTS.transform(point, transform);
I know the transform is not correct, as when i use an online tool it gives me the correct coords. http://www.environment.gov.au/cgi-bin/transform/mga2geo%5Fgda.pl?east=336301&north=6253363&zone=56
Source: (StackOverflow)
We are building a service for uploading zip-files containing an ESRI-shapefile. The service should be able to read the shapefile and do stuff with its content. So I've built a class that unzips the zip-file to temporary folder (subfolder of System.getProperty("java.io.tmpdir")).
Another class calls the unzip method from the Unzip-class and it then tries to read the unpacked shapefile using Geotools. It uses the Geotools DataStoreFinder.getDataStore(Map params) method to create a datastore from the unzipped shapefile. Here the problem occurs: the getDataStore-method returns null. I tested the URL, it looks allright. The file from which the URL derives exists, is a file and can be read by the application (tested using shapefile.exists(), shapefile.isFile(), shapefile.canRead()). So , what could be wrong? Why do I get null returned?
Here's the (relevant) code:
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFinder;
import org.geotools.data.FeatureSource;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import com.geodan.equus.entity.dataset.BasicFeature;
import com.geodan.equus.exception.EquusException;
import com.geodan.equus.processor.EquusProcessor;
import com.geodan.util.io.UnzipUtils;
import com.vividsolutions.jts.geom.Geometry;
public class ShapefileProcessor implements EquusProcessor
{
private static final File TEMP_UNZIP_DIR = new File(
System.getProperty("java.io.tmpdir") + File.separator
+ "atlas_temp_unzip_dir");
public static Set<BasicFeature> importFeatures(final File zipFile)
throws EquusException
{
// Check if the input file has the zipfile extension
if (!zipFile.getName().endsWith(".zip"))
{
throw new EquusException(
"The file is not a zipfile. It cannot be processed.");
}
// Unzip the file
try
{
UnzipUtils.unzip(zipFile, TEMP_UNZIP_DIR);
}
catch (IOException error)
{
throw new EquusException("The zipfile cannot be unzipped.", error);
}
// Validate whether the unzipped folder contains a shapefile and return it
File shapefile = new File("");
try
{
shapefile = findShapefile(TEMP_UNZIP_DIR);
}
catch (IOException error)
{
throw new EquusException(
"The zipfile does not contain a shapefile. Cannot process its contents.",
error);
}
// Collect the features from the shapefile and put them into an iterator
FeatureIterator<SimpleFeature> featureIterator;
try
{
featureIterator = readShapefile(shapefile);
}
catch (EquusException e)
{
throw new EquusException(e.getMessage(), e);
}
// Create a Set filled with the features in the FeatureIterator
Set<BasicFeature> features = createFeatureSet(featureIterator);
return features;
}
private static File findShapefile(File unzipPath) throws IOException
{
File shapefile = new File("");
// Find first .shp file in the unzip folder
File[] unzippedFiles = unzipPath.listFiles();
for (int i = 0; i < unzippedFiles.length; i++)
{
if (unzippedFiles[i].getName().endsWith(".shp"))
{
shapefile = new File(unzipPath + File.separator
+ unzippedFiles[i].getName());
break;
}
}
if (shapefile.toString() == "")
{
throw new IOException("No shapefile present in '" + unzipPath
+ "'.");
}
return shapefile;
}
private static FeatureIterator<SimpleFeature> readShapefile(File shapefile)
throws EquusException
{
// Collects the features from a shapefile and puts them into an iterator
FeatureCollection<SimpleFeatureType, SimpleFeature> featureCollection;
try
{
Map<String, URL> connectParameters = new HashMap<String, URL>();
connectParameters.put("url", shapefile.toURI().toURL());
DataStore dataStore = DataStoreFinder.getDataStore(connectParameters);
String typeName = dataStore.getTypeNames()[0];
FeatureSource<SimpleFeatureType, SimpleFeature> featureSource = dataStore.getFeatureSource(typeName);
featureCollection = featureSource.getFeatures();
}
catch (Exception e)
{
throw new EquusException(
"Features cannot be retrieved from the shapefile.", e);
}
return featureCollection.features();
}
private static Set<BasicFeature> createFeatureSet(
FeatureIterator<SimpleFeature> featureIterator)
{
SimpleFeature simpleFeature = null;
Set<BasicFeature> features = new HashSet<BasicFeature>();
while (featureIterator.hasNext())
{
simpleFeature = featureIterator.next();
BasicFeature feature = new BasicFeature();
feature.setGeometry((Geometry) simpleFeature.getDefaultGeometry());
features.add(feature);
}
return features;
}
}
Source: (StackOverflow)
XCode comes out of the box with support for Ant (with several sample projects you can generate).
How can I configure XCode to use maven pom.xml files?
Fore reference the project I am trying to set up is here:
It makes use of nested folders, each with their own pom.xml, all controlled with the usual maven build targets of:
- mvn clean install
- mvn install -o
- mvn install -o -DskipTests
What makes this a challenge is the nested modules; each of which installs into the local ~/.m2/repository.
For comparison: The eclipse build system references jars in the ~/.m2/repository for external dependencies, while still allowing modules in the project to refer to each other.
I would like a way to set up something similar for XCode.
Source: (StackOverflow)
I am looking for a Java library to display map data from various sources, including shapefile, WMS, WFS, Google Maps, possibly ArcIMS, etc. It seems like OpenLayers is the closest thing to what I want, except it's a JavaScript library, and I'm writing a Swing application.
GDAL looks promising, but as far as I can tell there won't be Java bindings until "sometime" in the future.
Just to be clear, I am looking for a single Java API that I can use to display maps from a number of map servers/sources.
Does anyone know if anything like this exists, and if not, where to go from here? Should I build this API on top of GeoTools? Or...
Source: (StackOverflow)
Any Geotools developers here? We discovered the following strange behaviour of GeometryJSON:
Geometry geom = getGeometry();
System.out.println(geom);
GeometryJSON g = new GeometryJSON();
StringWriter sw = new StringWriter();
try {
g.write(geom, sw);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(sw.toString());
outputs:
POLYGON((1.1212121214354352354235235423521 2.1212121121,4.454545454545445 3.454544545454454,10.515545445454 20.1545454654664, 1.1212121214354352354235235423521 2.1212121121))
{"type":"Polygon","coordinates":[[[1.1212,2.1212],[4.4545,3.4545],[10.5155,20.1545],[1.1212,2.1212]]]}
The polygon coordinates are rounded. Is this intended?
Source: (StackOverflow)
I'm currently using the GeoTools toolkit to do calculations on marine vessel data, such as calculating the Great Circle distance between two lon/lat points. I have two other requirements that I need to satisfy, but I'm not sure where to look in GeoTools to find classes to do these kind of calculations.
REQUIREMENT #1:
Calculate a Dead Reckoning position for a moving vessel.
INPUT VALUES:
- current longitude
- current latitude
- current speed (which can be easily converted to a distance, given a time 'T')
- current course
EXPECTED OUTPUTS:
- estimated longitude/latitude position after time 'T' has elapsed
REQUIREMENT #2:
Calculate the course from position 'A' to position 'B'.
INPUT VALUES:
- longitude 'A'
- latitude 'A'
- longitude 'B'
- latitude 'B'
EXPECTED OUTPUTS:
- course that points directly from 'A' to 'B'
QUESTION
Can anyone direct me to classes in GeoTools that are capable of performing these calculations? I'm overwhelmed by the sheer number of classes in GeoTools and I can't seem to find what I need to do this.
Source: (StackOverflow)
I'm new to use geotools. Now I need to generate a heat map showing the data density.
I found a Kernel density estimation process from here: https://jira.codehaus.org/browse/GEOT-4175, and so far it gives me a heatmap surface over a set of irregular data points as a GridCoverage2D.
My question is, how can I display it in a heat map fashion? Thanks a lot!!!
Source: (StackOverflow)
I am using JTS (from VividSolutions) and GeoTools. I have the following code:
public Geometry jsonToGeom(String json) throws IOException {
Geometry obj = new GeometryJSON().read(json);
return obj;
}
However, this returns the following RunTimeException:
java.lang.RuntimeException: java.lang.NoSuchMethodException: org.geotools.geojson.feature.FeatureHandler.<init>(com.vividsolutions.jts.geom.GeometryFactory)
at org.geotools.geojson.DelegatingHandler.createDelegate(DelegatingHandler.java:130)
at org.geotools.geojson.geom.GeometryHandler.primitive(GeometryHandler.java:68)
at org.json.simple.parser.JSONParser.parse(Unknown Source)
at org.json.simple.parser.JSONParser.parse(Unknown Source)
at org.geotools.geojson.GeoJSONUtil.parse(GeoJSONUtil.java:236)
at org.geotools.geojson.geom.GeometryJSON.parse(GeometryJSON.java:655)
at org.geotools.geojson.geom.GeometryJSON.read(GeometryJSON.java:196)
at am.abhi.experiments.geotoolstest.GeoJson.jsonToGeom(GeoJson.java:13)
at am.abhi.experiments.geotoolstest.SomeTest.testSomething(SomeTest.java:22)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at junit.framework.TestCase.runTest(TestCase.java:176)
at junit.framework.TestCase.runBare(TestCase.java:141)
at junit.framework.TestResult$1.protect(TestResult.java:122)
at junit.framework.TestResult.runProtected(TestResult.java:142)
at junit.framework.TestResult.run(TestResult.java:125)
at junit.framework.TestCase.run(TestCase.java:129)
at junit.framework.TestSuite.runTest(TestSuite.java:255)
at junit.framework.TestSuite.run(TestSuite.java:250)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:84)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
Caused by: java.lang.NoSuchMethodException: org.geotools.geojson.feature.FeatureHandler.<init>(com.vividsolutions.jts.geom.GeometryFactory)
at java.lang.Class.getConstructor0(Class.java:2849)
at java.lang.Class.getConstructor(Class.java:1718)
at org.geotools.geojson.DelegatingHandler.createDelegate(DelegatingHandler.java:123)
... 33 more
On stepping through the code, I found this method in org.geotools.geojson.DelegatingHandler which causes the error:
protected IContentHandler createDelegate(Class clazz, Object[] args) {
try {
if (args != null && args.length > 0) {
Class[] types = new Class[args.length];
for (int i = 0; i < args.length; i++) {
types[i] = args[i].getClass();
}
return (IContentHandler) clazz.getConstructor(types).newInstance(args);
}
else {
return (IContentHandler) clazz.newInstance();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
on line return (IContentHandler) clazz.getConstructor(types).newInstance(args)
.
It fails when it calls FeatureHandler and tries to pass a GeometryFactory as an argument. I am on JTS 1.8 and GeoTools 13-SNAPSHOT.
Any help or workaround would be appreciated.
Source: (StackOverflow)
I need to read a WFS transaction from the client (OpenLayers) and do the appropriate action. I want to use geoTools! Is there a way to implement a wfs server?
Suppose I have a Transacion like this:
<wfs:Transaction service=”WFS” version=”1.0.0″
xmlns:myns=”http://www.domain.com/ns“
xmlns:ogc=”http://www.opengis.net/ogc”
xmlns:wfs=”http://www.opengis.net/wfs”>
<wfs:Update typeName=”myns:LayerToUpdate“>
<wfs:Property>
<wfs:Name>propertyToUpdate</wfs:Name>
<wfs:Value>updatedValue</wfs:Value>
</wfs:Property>
<ogc:Filter>
<ogc:PropertyIsEqualTo>
<ogc:PropertyName>constraintProperty</ogc:PropertyName>
<ogc:Literal>constraintValue</ogc:Literal>
</ogc:PropertyIsEqualTo>
</ogc:Filter>
</wfs:Update>
</wfs:Transaction>
It will be appreciated If you suggest another way to do that!
Source: (StackOverflow)