我正在尝试使用GeoTools
将形状文件加载到java中,然后检查一个点是否位于形状文件中的多边形之一内
问题是我无法加载形状文件,因此无法继续前进。
这是到目前为止我的代码:
public static void main(String[] args){
// create sample coordinate
double lon = -105.0;
double lat = 40.0;
GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(PrecisionModel.maximumPreciseValue),8307);
Geometry point = geometryFactory.createPoint(new Coordinate(lon,lat));
//
String path = System.getProperty("user.dir") + "/continent_shp/continent_shp.shp";
File file = new File(path);
try {
Map<String, Serializable> connectParameters = new HashMap<String, Serializable>();
// load shapefile ---- does not work !!!!!!!!
connectParameters.put("url", file.toURI().toURL());
connectParameters.put("create spatial index", true);
DataStore dataStore = DataStoreFinder.getDataStore(connectParameters);
//
FeatureSource featureSource = dataStore.getFeatureSource("POLYGON");
FeatureCollection collection = (FeatureCollection) featureSource.getFeatures();
FeatureIterator iterator = collection.features();
while (iterator.hasNext()) {
Feature feature = iterator.next();
Geometry sourceGeometry = feature.getDefaultGeometry();
boolean isContained = sourceGeometry.contains(point);
System.out.println(isContained);
}
}
catch (MalformedURLException e) {e.printStackTrace();}
catch (IOException e) {e.printStackTrace();}
}
问题是在我尝试加载 shapefile 后,dataStore
变量为空。
这是我的导入:
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;
import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFinder;
import org.geotools.data.FeatureSource;
import org.geotools.feature.Feature;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.PrecisionModel;
有人能解释一下这个问题吗? 任何帮助,将不胜感激。 谢谢。
最佳答案
最可能的问题是您的路径上没有可用的 Shapefile 数据存储实现。请尝试以下方法来检查有哪些商店可用:
public Map<String, DataStoreFactorySpi> fetchAvailableDataStores() {
Iterator<DataStoreFactorySpi> it = DataStoreFinder.getAllDataStores();
while (it.hasNext()) {
DataStoreFactorySpi fac = it.next();
System.out.println(fac.getDisplayName());
}
}
另一个可能出错的地方是文件到 URL 的转换,尤其是在文件名或路径中有空格的情况下。尝试使用 DataUtilities.fileToURL(file)
代替。
关于java - 无法使用 GeoTools 加载 shapefile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43651504/