Skip to content

Instantly share code, notes, and snippets.

@All4Gis
Created August 9, 2018 11:36
Show Gist options
  • Save All4Gis/79872482ca8e64eab2c9f7b5c56e6a86 to your computer and use it in GitHub Desktop.
Save All4Gis/79872482ca8e64eab2c9f7b5c56e6a86 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
# encoding: utf-8
# Camaras de trafico de la DGT (España) directamente desde datos Datex
import xmltodict
import requests
import base64
import json
from qgis.core import QgsProject, QgsFeature
__author__ = 'Fran Raga'
__version__ = 0.1
__date__ = '2018-07-29'
__updated__ = '2018-07-29'
PREDEFINED_LOCATIONS_URL = 'http://infocar.dgt.es/datex2/dgt/CCTVSiteTablePublication/all/content.xml'
settings = QSettings()
def CreateMarker(layer, lista_camaras):
layer.startEditing()
categorized = []
for camara in lista_camaras:
id = camara['@id']
if id == "GUID_CAM_15":
break
version = camara['@version']
identificacion = camara['_0:cctvCameraIdentification']
tipo = camara['_0:cctvCameraType']
lat = camara['_0:cctvCameraLocation']['_0:locationForDisplay']['_0:latitude']
lon = camara['_0:cctvCameraLocation']['_0:locationForDisplay']['_0:longitude']
url = camara['_0:cctvStillImageService']['_0:stillImageUrl']['_0:urlLinkAddress']
feature = QgsFeature()
p = QgsPointXY()
p.set(float(lon), float(lat))
geom = QgsGeometry.fromPointXY(p)
feature.setGeometry(geom)
feature.setAttributes(
[id, version, identificacion, tipo, lon, lat, url])
layer.addFeatures([feature])
Common(layer, url, id, categorized)
layer.commitChanges()
layer.updateExtents()
layer.triggerRepaint()
def UpdateMarkers():
print ("Actualizando Camaras")
categorized = []
layer = QgsProject.instance().mapLayersByName("Camaras")[0]
for feature in layer.getFeatures():
url = feature["url"]
id = feature["id"]
Common(layer, url, id, categorized)
layer.triggerRepaint()
print ("Camaras Actualizadas")
return
def Common(layer, url, value, categorized):
svg = """<?xml version="1.0" encoding="UTF-8" standalone="no"?><svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><image xlink:href="data:image/jpeg;base64,{0}" height="320" width="420" /></svg>"""
data = requests.get(url, stream=True).content
b64response = base64.b64encode(data)
newsvg = svg.format(b64response.decode("utf-8")).replace('\n', '')
path = r"D:\temp\cam\{0}.svg".format(value)
with open(path, 'w') as f:
f.write(newsvg)
svgStyle = {}
svgStyle['name'] = path
svgStyle['size'] = '30'
sym_image = QgsSvgMarkerSymbolLayer.create(svgStyle)
symbol = QgsSymbol.defaultSymbol(layer.geometryType())
symbol.changeSymbolLayer(0, sym_image)
new_category = QgsRendererCategory(str(value), symbol, str(value))
categorized.append(new_category)
renderer = QgsCategorizedSymbolRenderer("id", categorized)
layer.setRenderer(renderer)
return
def CreateCameras():
data = requests.get(PREDEFINED_LOCATIONS_URL)
xpars = xmltodict.parse(data.text)
parse = json.dumps(xpars)
resp_dict = json.loads(parse)
lista_camaras = resp_dict['_0:d2LogicalModel']['_0:payloadPublication']['_0:genericPublicationExtension'][
'_0:cctvSiteTablePublication']['_0:cctvCameraList']['_0:cctvCameraMetadataRecord']
crs = QgsCoordinateReferenceSystem('EPSG:4326')
uri = 'Point?crs=' + crs.authid() + '&'
fields = ["id", "version", "identificacion", "tipo", "lat", "lon", "url"]
fieldsdesc = ['field=' + f for f in fields]
fieldsstring = '&'.join(fieldsdesc)
uri += fieldsstring
layer = QgsVectorLayer(uri, "Camaras", "memory")
CreateMarker(layer, lista_camaras)
prjSetting3 = settings.value('/Projections/defaultBehavior')
settings.setValue('/Projections/defaultBehavior', '')
QgsProject.instance().addMapLayer(layer, True)
settings.setValue('/Projections/defaultBehavior', prjSetting3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment