假设我将一个Shapefile放在一起,所有要素的顶点都移动了恒定量。转移所有特征的最简单方法是什么(因此(x,y),其顶点位置)进行任意偏移?我有很多文件要应用此更正,因此首选Bash / OGR答案:)
最后,我最终使用了Spatialite,因为它具有不错的功能ShiftCoords
。但是,该线程非常有用!谢谢大家!
假设我将一个Shapefile放在一起,所有要素的顶点都移动了恒定量。转移所有特征的最简单方法是什么(因此(x,y),其顶点位置)进行任意偏移?我有很多文件要应用此更正,因此首选Bash / OGR答案:)
最后,我最终使用了Spatialite,因为它具有不错的功能ShiftCoords
。但是,该线程非常有用!谢谢大家!
Answers:
ShapefileReader t file: "shapefile.shp";
out = select * except (GEOMETRY), Geom.translate(GEOMETRY,100,100) from t;
ShapefileWriter out file: "ahapefile_shift.shp";
我设计了Fiona(OGR包装器)来简化这种处理。
from fiona import collection
import logging
log = logging.getLogger()
# A few functions to shift coords. They call eachother semi-recursively.
def shiftCoords_Point(coords, delta):
# delta is a (delta_x, delta_y [, delta_y]) tuple
return tuple(c + d for c, d in zip(coords, delta))
def shiftCoords_LineString(coords, delta):
return list(shiftCoords_Point(pt_coords, delta) for pt_coords in coords)
def shiftCoords_Polygon(coords, delta):
return list(
shiftCoords_LineString(ring_coords, delta) for ring_coords in coords)
# We'll use a map of these functions in the processing code below.
shifters = {
'Point': shiftCoords_Point,
'LineString': shiftCoords_LineString,
'Polygon': shiftCoords_Polygon }
# Example 2D shift, 1 unit eastward and northward
delta = (1.0, 1.0)
with collection("original.shp", "r") as source:
# Create a sink for processed features with the same format and
# coordinate reference system as the source.
with collection(
"shifted.shp",
"w",
driver=source.driver,
schema=source.schema,
crs=source.crs
) as sink:
for rec in source:
try:
g = rec['geometry']
g['coordinates'] = shifters[g['type']](
g['coordinates'], delta )
rec['geometry'] = g
sink.write(rec)
except Exception, e:
log.exception("Error processing record %s:", rec)
更新:我在http://sgillies.net/blog/1128/geoprocessing-for-hipsters-translator-features上放置了该脚本的另一个更严格的版本。
尽管该帖子用python标记,但由于已经提到了JEQL,因此下面是一个JavaScript示例(使用GeoScript)。
/**
* Shift all coords in all features for all layers in some directory
*/
var Directory = require("geoscript/workspace").Directory;
var Layer = require("geoscript/layer").Layer;
// offset for all geometry coords
var dx = dy = 10;
var dir = Directory("./data");
dir.names.forEach(function(name) {
var orig = dir.get(name);
var shifted = Layer({
schema: orig.schema.clone({name: name + "-shifted"})
});
orig.features.forEach(function(feature) {
var clone = feature.clone();
clone.geometry = feature.geometry.transform({dx: dx, dy: dy});
shifted.add(clone);
});
dir.add(shifted);
});
使用使用SQLite和SpatiaLite编译的GDAL> = 1.10.0:
ogr2ogr data_shifted.shp data.shp -dialect sqlite -sql "SELECT ShiftCoords(geometry,1,10) FROM data"
其中shiftX = 1和shiftY = 10。
GRASS GIS v.edit模块:
假定匹配投影中存在现有位置和地图集。
在shell脚本中:
#!/bin/bash
for file in `ls | grep \.shp$ | sed 's/\.shp$//g'`
do
v.in.ogr dsn=./${file}.shp output=$file
v.edit map=$file tool=move move=1,1 where="1=1"
v.out.ogr input=$file type=point,line,boundary,area dsn=./${file}_edit.shp
done
或在Python脚本中:
#!/usr/bin/env python
import os
from grass.script import core as grass
for file in os.listdir("."):
if file.endswith(".shp"):
f = file.replace(".shp","")
grass.run_command("v.in.ogr", dsn=file, output=f)
grass.run_command("v.edit", map=f, tool="move", move="1,1", where="1=1")
grass.run_command("v.out.ogr", input=f, type="point,line,boundary,area", dsn="./%s_moved.shp" % f)
另一个选择是仅在ogr2ogr中使用重投影选项,这肯定比JEQL,Fiona或GeoScript方法更骇人,但仍然有效。请注意,只要在s_srs和t_srs中使用的投影之间发生变化的唯一错误是虚假的向东和向北,则from和to投影就不必真正是原始shapefile的实际投影。在此示例中,我仅使用Google Mercator。我确信有一个更简单的坐标系可以用作基础,但是这个正好在我面前进行复制/粘贴。
ogr2ogr -s_srs EPSG:900913 -t_srs 'PROJCS["Google Mercator",GEOGCS["WGS 84",DATUM["World Geodetic System 1984",SPHEROID["WGS 84",6378137.0,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0.0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.017453292519943295],AXIS["Geodetic latitude",NORTH],AXIS["Geodetic longitude",EAST],AUTHORITY["EPSG","4326"]],PROJECTION["Mercator_1SP"],PARAMETER["semi_minor",6378137.0],PARAMETER["latitude_of_origin",0.0],PARAMETER["central_meridian",0.0],PARAMETER["scale_factor",1.0],PARAMETER["false_easting",1000.0],PARAMETER["false_northing",1000.0],UNIT["m",1.0],AXIS["Easting",EAST],AXIS["Northing",NORTH],AUTHORITY["EPSG","900913"]]' -f "ESRI Shapefile" shift.shp original.shp
或者,要保存键入/粘贴内容,请将以下内容保存到projcs.txt
(与上面相同,但删除了单引号):
-s_srs EPSG:900913
-t_srs PROJCS["Google Mercator",GEOGCS["WGS 84",DATUM["World Geodetic System 1984",SPHEROID["WGS 84",6378137.0,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0.0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.017453292519943295],AXIS["Geodetic latitude",NORTH],AXIS["Geodetic longitude",EAST],AUTHORITY["EPSG","4326"]],PROJECTION["Mercator_1SP"],PARAMETER["semi_minor",6378137.0],PARAMETER["latitude_of_origin",0.0],PARAMETER["central_meridian",0.0],PARAMETER["scale_factor",1.0],PARAMETER["false_easting",1000.0],PARAMETER["false_northing",1000.0],UNIT["m",1.0],AXIS["Easting",EAST],AXIS["Northing",NORTH],AUTHORITY["EPSG","900913"]]
然后运行:
ogr2ogr --optfile projcs.txt shifted.shp input.shp
--optfile
,如ogr2ogr --optfile projcs.txt shifted.shp input.shp
。我将它折叠成答案。
使用包maptools及其elide函数的R选项:
shift.xy <- c(1, 2)
library(maptools)
files <- list.files(pattern = "shp$")
for (fi in files) {
xx <- readShapeSpatial(fi)
## update the geometry with elide arguments
shifted <- elide(xx, shift = shift.xy)
## write out a new shapfile
writeSpatialShape(shifted, paste("shifted", fi, sep = ""))
}
在地理功能中使用shapefile解析器,可以使用XSLT执行该过程。当然,之后您需要将其转换回shapefile :-)。
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="2.0" xmlns:gml="http://www.opengis.net/gml">
<xsl:param name="x_shift" select="0.0"/>
<xsl:param name="y_shift" select="0.0"/>
<!-- first the identity transform makes sure everything gets copied -->
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<!-- for any element with coordinate strings, apply the translation factors -->
<!-- note that a schema-aware processor could use the schema type names to simplify -->
<xsl:template match="gml:pos|gml:posList|gml:lowerCorner|gml:upperCorner">
<xsl:copy>
<!-- this xpath parses the ordinates, assuming x y ordering (shapefiles), applies translation factors -->
<xsl:value-of select="
for $i in tokenize(.,'\s+') return
if ($i[(position() mod 2) ne 0]) then
number($i)+$x_shift
else
number($i)+$y_shift
"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
这是Groovy GeoScript版本:
import geoscript.workspace.Directory
import geoscript.layer.Layer
int dx = 10
int dy = 10
def dir = new Directory("./data")
dir.layers.each{name ->
def orig = dir.get(name)
def shifted = dir.create("${name}-shifted", orig.schema.fields)
shifted.add(orig.cursor.collect{f ->
f.geom = f.geom.translate(dx, dy)
f
})
}
这是OGR版本
驱动程序= ogr.GetDriverByName(“ ESRI Shapefile”)
def移动(dx,dy,dz):
dataSource = driver.Open(path,1)
layer = dataSource.GetLayer(0)
for feature in layer:
get_poly = feature.GetGeometryRef()
get_ring = get_poly.GetGeometryRef(0)
points = get_ring.GetPointCount()
set_ring = ogr.Geometry(ogr.wkbLinearRing)
for p in xrange(points):
x,y,z = get_ring.GetPoint(p)
x += dx
y += dy
z += dz
set_ring.AddPoint(x,y)
print x,y,z
set_poly = ogr.Geometry(ogr.wkbPolygon)
set_poly.AddGeometry(set_ring)
feature.SetGeometry(set_poly)
layer.SetFeature(feature)
del layer
del feature
del dataSource