Last active
October 31, 2021 08:04
-
-
Save sickel/a2e098addec57b39f79ee0422d5f79dd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def measureline(search,reverse=False,offset=0): | |
""" | |
To be run in the QGIS python console. Select a line, run measureline(<search>) and it will put a marker at the point | |
<search> mapunits along the line from the start of the line and print out the lat,lon of the point. | |
By either setting a negative search length or setting reverse to True, it will measure from the end of the line instead. | |
A number given as <offset> will be subtracted from <search>. If an offset is given, search should be a positive value. | |
Developed in QGIS 3.20, will probably run in other 3.X version, will probably not work in QGIS 2.X | |
""" | |
search=search-offset | |
if search < 0: | |
if offset==0: | |
reverse=not(reverse) | |
search=-1*search | |
else: | |
print("ugyldig avstand") | |
return(None) | |
layer=iface.activeLayer() | |
layerCrs=layer.crs().authid() | |
crsSrc=QgsCoordinateReferenceSystem(layerCrs) | |
trfContext = QgsProject.instance().transformContext() | |
if len(layer.selectedFeatures())==0: | |
print('Må velge en linje') | |
return(None) | |
line = layer.selectedFeatures()[0] | |
geom = line.geometry() | |
totlength=geom.length() | |
print(f'Total lengde: {round(totlength)}') | |
if search > totlength: | |
print('For lang avstand') | |
print(f'{round(search-abs(totlength))} overskytende') | |
return(None) | |
if reverse: | |
search=totlength-search | |
canvas=iface.mapCanvas() | |
marker=QgsVertexMarker(canvas) | |
projCrs=canvas.mapSettings().destinationCrs().authid() | |
xy=QgsPointXY(line.geometry().interpolate(search).vertices().next()) | |
if projCrs != layerCrs: | |
#The marker is drawn directly at the canvas, so it need to be in the canvas' projection | |
crsProj=QgsCoordinateReferenceSystem(projCrs) | |
xform=QgsCoordinateTransform(crsSrc,crsProj,trfContext) | |
xy=xform.transform(xy) | |
marker.setCenter(xy) | |
marker.setColor(QColor(255,0, 0)) | |
marker.setIconSize(15) | |
marker.setIconType(QgsVertexMarker.ICON_X) | |
marker.setPenWidth(3) | |
crsSrc=QgsCoordinateReferenceSystem(layerCrs) | |
crsTrg=QgsCoordinateReferenceSystem("EPSG:4326") | |
trfContext = QgsProject.instance().transformContext() | |
xform=QgsCoordinateTransform(crsSrc,crsTrg,trfContext) | |
latlon=xform.transform(xy) | |
print(f'{round(latlon.y(),6)},{round(latlon.x(),6)}') | |
return(marker) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment