Skip to content

Instantly share code, notes, and snippets.

@AndreLester
Last active September 15, 2015 21:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndreLester/36bc44fd703b53c53496 to your computer and use it in GitHub Desktop.
Save AndreLester/36bc44fd703b53c53496 to your computer and use it in GitHub Desktop.
Create lines using a point from a shapefile and getting the ID's and angles from a CSV file
import math
from qgis.core import QgsFeature
pointLayerName = "point" #change to whatever name of point layer is
lineLayerName = "lines" #change to whatever name of line layer is
#be sure to draw one point, leave line layer empty
#find layer objects by name
layers = QgsMapLayerRegistry.instance().mapLayers()
for name, layer in layers.iteritems():
print "%s %s" % (layer.name(),layer)
if layer.name() == lineLayerName:
lineLayer = layer
if layer.name() == pointLayerName:
pointLayer = layer
assert pointLayer != None
assert lineLayer != None
#find point by ID
expr = QgsExpression( "id=1" )
it = pointLayer.getFeatures( QgsFeatureRequest( expr ) )
for f in it:
geompoint = f.geometry()
pivot = geompoint.asPoint()
break
#generate lines from provided degrees (LOBs)
lineLayer.beginEditCommand("Add Spokes")
provider = lineLayer.dataProvider()
lobfeat = lineLayer.getFeatures()
linefeatures=[]
for x in lobfeat:
lobvals = x.attributes()
lob = lobvals[1] #searches column 2 of line feature for LOBs
geomspoke = QgsGeometry.fromPolyline([QgsPoint(0.0,0.0),QgsPoint(0.0,10.0)])
geomspoke.rotate(float(ang),QgsPoint(0.0,0.0))
geomspoke.translate(pivot.x(),pivot.y())
print geomspoke.exportToWkt(6)
spokefeat = QgsFeature()
spokefeat.setGeometry(geomspoke)
linefeatures.append(spokefeat)
provider.addFeatures(linefeatures)
lineLayer.commitChanges()
lineLayer.endEditCommand()
print "Done!"
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Line Generator\n",
"\n",
"Read a point from a given shapefile. Generate lines around this point at an angle read from a CSV giving them ID's also obtained from the CSV. \n",
"\n",
"Dependencies:\n",
"[pyshp](https://github.com/cleder/pyshp) \n",
"\n",
"It is a pure Python library just install with:\n",
"\n",
" pip install pyshp \n",
" \n",
"[Fiona](http://toblerity.org/fiona/manual.html) is a very good alternative. Althought not pure Python and a bit more complicated."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import math\n",
"import csv\n",
"import shapefile\n",
"\n",
"\n",
"# Change this to point to your shapefile\n",
"sf = shapefile.Reader('./VillageRes.shp')\n",
"\n",
"shapes = sf.shapes()\n",
"x, y = (shapes[0].points[0])\n",
"\n",
"del sf # Not sure how to close a shapefile"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The following cell just generates a test file to generate the lines."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Overwriting ./lines.csv\n"
]
}
],
"source": [
"%%writefile ./lines.csv\n",
"1, 90\n",
"2, 100\n",
"3, 40\n",
"4, 300"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"w = shapefile.Writer(shapefile.POLYLINE)\n",
"\n",
"w.field('ID','C','16')\n",
"w.field('LOB','N','8')\n",
"\n",
"# Replace with your own CSV file\n",
"with open('lines.csv') as line_in:\n",
" reader = csv.reader(line_in, delimiter=',')\n",
" for rec in reader:\n",
" #print(rec)\n",
" no, angle = rec[0], float(rec[1])\n",
" line_len = 10\n",
" angle_rad = math.radians(angle)\n",
" dx = line_len*math.sin(angle_rad)\n",
" dy = line_len*math.cos(angle_rad)\n",
" x2, y2 = x+dx, y+dy\n",
" w.line(parts=[[[x,y],[x2,y2]]])\n",
" w.record(ID=no, LOB=angle)\n",
" \n",
"w.save('./line.shp')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.4.3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment