Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

I added a QgsComposerScaleBar to a QgsComposition.

I wish to have segment rounded to the nearest km but I don't know how to achieve this.

Thank you in advance.

share|improve this question

1 Answer 1

After browsing the documentation a little more, here is how I'd do it :

# Create the scale bar and position it
x, y = 217, 192
w, h = 35, 18
scalebar = QgsComposerScaleBar(composition)
scalebar.setItemPosition(x, y, w, h)
scalebar.setStyle('Single Box')
scalebar.setComposerMap(map)
scalebar.setFrame(False)

# The default map unit is "meters", but you wanted the scalebar in "km"
# The map has to have an appropriate coordinate system, though.
# WGS84 won't work, for instance, as it uses angular units.
scalebar.setNumMapUnitsPerScaleBarUnit(1000)
scalebar.setUnitLabeling("km")

# Find out the total size of the scalebar, in map units (m)
scalebar_size = map.extent().width() / map.rect().width() * w

# Convert it to km
scalebar_size /= 1000.

# Find the size of a segment
number_of_segments = 2
segment_size = scalebar_size / number_of_segments

# Round it to the nearest km, with a minimum of 1 km
# Note that for smaller maps this will create a huge scalebar!
segment_size = max(1, round(segment_size))

# Divide the scalebar
scalebar.setNumSegmentsLeft(0)
scalebar.setNumSegments(number_of_segments)
scalebar.setNumUnitsPerSegment(segment_size)

# Finally, add the scalebar to the composition
composition.addItem(scalebar)
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.