Wednesday 13 February 2019

Extracting coordinates - user friendly tool (3) (QGIS Plugin) - getting WKT string

If we have extracted coordinates, it would be nice to automatically to do something useful with them - creates points, line or polygon. So, next step is to add possibility to get WKT string  or create features such points, lines and polygonx. WKT  can be very handy - in case we want to copy and paste 'coordinates' into SQL statements in PostGIS for example.

Let's start with adding new widgets to our form:
QComboBox: comboBoxFeatureType - to define what kind of feature we want to create (Point, Line, Polygon)
QPushButton: pushButtonGetWKTString -
QTextEdit: textEditRawTextWKRTString

First we need to get DD format of coordinates stored in table. At the end we are going to create points, line or polygon features from extracted points so it will be convenient to operate on QgsPointXY class which are needed to create those features.

For each row in table we are going to:
create CoordinatePair class to convert extracted latitude and longitude into DD format:

for i in range(0, points_count):
    point_coordinates = agt.CoordinatesPair(self.dlg.tableWidgetCoordinates.item(i, 0).text(),
                                            self.dlg.tableWidgetCoordinates.item(i, 1).text())

If DD format of latitude and longitude is calculated (extracted values are valid) create QgsPointXY feature append it to points list:


if point_coordinates.is_valid is True:
    point = QgsPointXY(point_coordinates.lon_dd, point_coordinates.lat_dd)
    points.append(point)
 
Note: During extraction of coordinates we don't check if it is correct, e. g. if minutes are less than
etc.

WKT strings depends on what type of geometry we want create from text. Because we creates geometry - this is our main purpose of this plugin - we can get WKT string easily from just created geometry using asWkt() method of QgsPoint and QgsGeometry classes:

if geom_type == GEOM_POINT:
    for point_item in points:
        wkt_str += point_item.asWkt()
elif geom_type == GEOM_LINE:
    line_geom = QgsGeometry.fromPolylineXY(points)
    wkt_str = line_geom.asWkt()
elif geom_type == GEOM_POLYGON:
    polygon_geom = QgsGeometry.fromPolygonXY([points])
    wkt_str = polygon_geom.asWkt()

And another example how it works: this time I want to get coordinates of points from plain text (Note: presented data is not for navigational or any other use!). As you can see this tool can bring a great benefit of time because you don't have to extract spatial data from text manually.

No comments:

Post a Comment