forked from warrieka/geopunt4Qgis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgipodHelper.py
187 lines (166 loc) · 7.88 KB
/
gipodHelper.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
# -*- coding: utf-8 -*-
"""
/***************************************************************************
gipodeoHelper
A QGIS plugin
"Tool om geopunt in QGIS te gebruiken"
-------------------
begin : 2013-12-08
copyright : (C) 2013 by Kay Warrie
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
import os.path, datetime, urllib2
from PyQt4.QtCore import *
from PyQt4.QtGui import QFileDialog, QColor
from qgis.core import *
class gipodeoHelper:
@staticmethod
def openOutput(sender=None, startFolder=None):
fd = QFileDialog()
filter = "ESRI Shape File (*.shp);;Comma separated value File (excel) (*.csv);;geojson (*.geojson);;GML File (*.gml);;MapInfo TAB (*.tab);;SpatiaLite (*.sqlite);;KML (google earth) (*.kml)"
fName = fd.getSaveFileName( sender, "open file", filter=filter, directory=startFolder)
if fName:
return fName
else:
return None
@staticmethod
def checkFtype( file2check):
fType = "ESRI Shapefile" #DEFAULT
if file2check:
if file2check.upper().endswith('SHP'):
fType = "ESRI Shapefile"
elif file2check.upper().endswith('GML'):
fType = "GML"
elif file2check.upper().endswith('GEOJSON'):
fType = "GeoJSON"
elif file2check.upper().endswith('CSV'):
fType = "CSV"
elif file2check.upper().endswith('KML'):
fType = "KML"
elif file2check.upper().endswith('SQLITE'):
fType = "SQLite"
elif file2check.upper().endswith('TAB'):
fType = "MapInfo File"
return fType
else:
return None
class gipodWriter:
def __init__(self, iface, layername, CRS=31370, manifestation=False, KML="" ):
self.iface = iface
self.canvas = iface.mapCanvas()
self.layername = layername
self.CRS = CRS
self.manifestation = manifestation
if KML == "KML":
self.KML = 1
else:
self.KML = 0
def __enter__(self):
attributes =[ QgsField("gipodId", QVariant.Int),
QgsField("owner", QVariant.String) ,
QgsField("description", QVariant.String),
QgsField("beginDate", QVariant.String, "Date"),
QgsField("endDate", QVariant.String, "Date"),
QgsField("hinder", QVariant.Int),
QgsField("link", QVariant.String),
QgsField("cities", QVariant.String)
]
if self.manifestation:
attributes += [QgsField("intiatief", QVariant.String),
QgsField("patroon", QVariant.String)]
if self.KML:
attributes += [QgsField("begin", QVariant.String, "Date"),
QgsField("end", QVariant.String, "Date"),
QgsField("icon", QVariant.String)
]
self.gipodlayer = QgsVectorLayer("Point", self.layername, "memory")
self.gipodProvider = self.gipodlayer.dataProvider()
self.gipodProvider.addAttributes(attributes)
self.gipodlayer.updateFields()
self.fields= self.gipodlayer.pendingFields()
return self
def saveGipod2file(self, filename, ftype="ESRI Shapefile" ):
layerOptions = []
datasourceOptions = []
if ftype == "CSV":
layerOptions += ["GEOMETRY=AS_XY","SEPARATOR=SEMICOLON"]
if ftype == "KML":
datasourceOptions += ["NameField=owner"]
srs = QgsCoordinateReferenceSystem(self.CRS)
fpath, name = os.path.split(filename)
if fpath and os.path.exists(fpath):
error = QgsVectorFileWriter.writeAsVectorFormat(self.gipodlayer , filename, "utf-8", self.gipodlayer.crs(), ftype, layerOptions= layerOptions, datasourceOptions= datasourceOptions )
if error == QgsVectorFileWriter.NoError:
if ftype == "CSV":
uri =( "file:///%s?delimiter=%s&xField=%s&yField=%s&crs=%s" % (
filename, ";", "X", "Y", self.gipodlayer.crs().authid()) ).replace("\\","/")
self.gipodlayer = QgsVectorLayer(uri, self.layername, "delimitedtext")
else:
self.gipodlayer = QgsVectorLayer( filename, self.layername, "ogr")
self.gipodProvider = self.gipodlayer.dataProvider()
else:
raise gipodError( str(error.hasError()) )
else:
raise gipodError( fpath + " doesn't exist" )
def _makeCRSpoint(self, xy):
x,y = xy
fromCrs = QgsCoordinateReferenceSystem(self.CRS)
xform = QgsCoordinateTransform( fromCrs, self.gipodlayer.crs() )
return xform.transform( QgsPoint( x,y ))
def writePoint(self, xy, gipodId, owner, description, startDateTime, endDateTime, importantHindrance, detail, cities=[], initiator=None, recurrencePattern=None):
fet = QgsFeature(self.fields)
fet['gipodId'] = gipodId
fet['owner'] = owner
fet['description'] = description
if self.KML:
fet['begin'] = startDateTime.split("T")[0]
fet['end'] = endDateTime.split("T")[0]
if importantHindrance: fet['icon'] = "http://gipod.api.agiv.be/ws/v1/icon/workassignment?important=true"
else: fet['icon'] = "http://gipod.api.agiv.be/ws/v1/icon/workassignment?important=false"
fet['beginDate'] = startDateTime
fet['endDate'] = endDateTime
fet['hinder'] = importantHindrance
fet['link'] = detail
fet['cities'] = ", ".join(cities)
if initiator and self.manifestation:
fet['intiatief'] = initiator
if recurrencePattern and self.manifestation:
fet['patroon'] = recurrencePattern
prjPt = self._makeCRSpoint( xy )
fet.setGeometry(QgsGeometry.fromPoint(prjPt))
self.gipodProvider.addFeatures([ fet ])
def __exit__(self, type, value, traceback):
' add layer to map and clean up'
render = gipodRender(self.gipodlayer, 'hinder' ).render
self.gipodlayer.setRendererV2(render)
#self.gipodlayer.setEditType( 8, QgsVectorLayer.WebView)
QgsMapLayerRegistry.instance().addMapLayer(self.gipodlayer)
# refresh and update extends
self.gipodlayer.updateExtents()
self.canvas.refresh()
del self.gipodlayer, self.gipodProvider, self.fields
class gipodRender:
def __init__(self, Layer, hinderAttr='hinder'):
'1: in hinderAttr is veel hinder, 0: in hinderAttr is weinig hinder'
hinderSymbol = QgsSymbolV2.defaultSymbol( 0 ) #0=point
noHinderSymbol = QgsSymbolV2.defaultSymbol( 0 ) #Layer.geometryType()
hinderSymbol.setColor(QColor('#FF0000'))
noHinderSymbol.setColor(QColor('#FFFF00'))
noHinder= QgsRendererCategoryV2(0, noHinderSymbol ,'weinig hinder')
hinder= QgsRendererCategoryV2(1, hinderSymbol ,'veel hinder')
self.render = QgsCategorizedSymbolRendererV2(hinderAttr,[noHinder,hinder])
print self.render
class gipodError(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return repr(self.message)