def testStringToFeatureList(self): """Test converting json string to features""" fields = QgsFields() fields.append(QgsField("name", QVariant.String)) # empty string features = QgsJSONUtils.stringToFeatureList("", fields, codec) self.assertEqual(features, []) # bad string features = QgsJSONUtils.stringToFeatureList("asdasdas", fields, codec) self.assertEqual(features, []) # geojson string with 1 feature features = QgsJSONUtils.stringToFeatureList( '{\n"type": "Feature","geometry": {"type": "Point","coordinates": [125, 10]},"properties": {"name": "Dinagat Islands"}}', fields, codec, ) self.assertEqual(len(features), 1) self.assertFalse(features[0].geometry().isEmpty()) self.assertEqual(features[0].geometry().wkbType(), QgsWkbTypes.Point) point = features[0].geometry().geometry() self.assertEqual(point.x(), 125.0) self.assertEqual(point.y(), 10.0) self.assertEqual(features[0]["name"], "Dinagat Islands") # geojson string with 2 features features = QgsJSONUtils.stringToFeatureList( '{ "type": "FeatureCollection","features":[{\n"type": "Feature","geometry": {"type": "Point","coordinates": [125, 10]},"properties": {"name": "Dinagat Islands"}}, {\n"type": "Feature","geometry": {"type": "Point","coordinates": [110, 20]},"properties": {"name": "Henry Gale Island"}}]}', fields, codec, ) self.assertEqual(len(features), 2) self.assertFalse(features[0].geometry().isEmpty()) self.assertEqual(features[0].geometry().wkbType(), QgsWkbTypes.Point) point = features[0].geometry().geometry() self.assertEqual(point.x(), 125.0) self.assertEqual(point.y(), 10.0) self.assertEqual(features[0]["name"], "Dinagat Islands") self.assertFalse(features[1].geometry().isEmpty()) self.assertEqual(features[1].geometry().wkbType(), QgsWkbTypes.Point) point = features[1].geometry().geometry() self.assertEqual(point.x(), 110.0) self.assertEqual(point.y(), 20.0) self.assertEqual(features[1]["name"], "Henry Gale Island")
def testStringToFields(self): """test retrieving fields from GeoJSON strings""" # empty string fields = QgsJSONUtils.stringToFields("", codec) self.assertEqual(fields.count(), 0) # bad string fields = QgsJSONUtils.stringToFields("asdasdas", codec) self.assertEqual(fields.count(), 0) # geojson string fields = QgsJSONUtils.stringToFields('{\n"type": "Feature","geometry": {"type": "Point","coordinates": [125, 10]},"properties": {"name": "Dinagat Islands","height":5.5}}', codec) self.assertEqual(fields.count(), 2) self.assertEqual(fields[0].name(), "name") self.assertEqual(fields[0].type(), QVariant.String) self.assertEqual(fields[1].name(), "height") self.assertEqual(fields[1].type(), QVariant.Double)
def testStringToFields(self): """test retrieving fields from GeoJSON strings""" # empty string fields = QgsJSONUtils.stringToFields("", codec) self.assertEqual(fields.count(), 0) # bad string fields = QgsJSONUtils.stringToFields("asdasdas", codec) self.assertEqual(fields.count(), 0) # geojson string fields = QgsJSONUtils.stringToFields( '{\n"type": "Feature","geometry": {"type": "Point","coordinates": [125, 10]},"properties": {"name": "Dinagat Islands","height":5.5}}', codec) self.assertEqual(fields.count(), 2) self.assertEqual(fields[0].name(), "name") self.assertEqual(fields[0].type(), QVariant.String) self.assertEqual(fields[1].name(), "height") self.assertEqual(fields[1].type(), QVariant.Double)
def testExportAttributes(self): """ test exporting feature's attributes to JSON object """ fields = QgsFields() # test empty attributes feature = QgsFeature(fields, 5) expected = "{}" self.assertEqual(QgsJSONUtils.exportAttributes(feature), expected) # test feature with attributes fields.append(QgsField("name", QVariant.String)) fields.append(QgsField("cost", QVariant.Double)) fields.append(QgsField("population", QVariant.Int)) feature = QgsFeature(fields, 5) feature.setGeometry(QgsGeometry(QgsPointV2(5, 6))) feature.setAttributes(['Valsier Peninsula', 6.8, 198]) expected = """{"name":"Valsier Peninsula", "cost":6.8, "population":198}""" self.assertEqual(QgsJSONUtils.exportAttributes(feature), expected)
def testStringToFeatureList(self): """Test converting json string to features""" fields = QgsFields() fields.append(QgsField("name", QVariant.String)) # empty string features = QgsJSONUtils.stringToFeatureList("", fields, codec) self.assertEqual(features, []) # bad string features = QgsJSONUtils.stringToFeatureList("asdasdas", fields, codec) self.assertEqual(features, []) # geojson string with 1 feature features = QgsJSONUtils.stringToFeatureList('{\n"type": "Feature","geometry": {"type": "Point","coordinates": [125, 10]},"properties": {"name": "Dinagat Islands"}}', fields, codec) self.assertEqual(len(features), 1) self.assertFalse(features[0].geometry().isEmpty()) self.assertEqual(features[0].geometry().wkbType(), QgsWkbTypes.Point) point = features[0].geometry().geometry() self.assertEqual(point.x(), 125.0) self.assertEqual(point.y(), 10.0) self.assertEqual(features[0]['name'], "Dinagat Islands") # geojson string with 2 features features = QgsJSONUtils.stringToFeatureList('{ "type": "FeatureCollection","features":[{\n"type": "Feature","geometry": {"type": "Point","coordinates": [125, 10]},"properties": {"name": "Dinagat Islands"}}, {\n"type": "Feature","geometry": {"type": "Point","coordinates": [110, 20]},"properties": {"name": "Henry Gale Island"}}]}', fields, codec) self.assertEqual(len(features), 2) self.assertFalse(features[0].geometry().isEmpty()) self.assertEqual(features[0].geometry().wkbType(), QgsWkbTypes.Point) point = features[0].geometry().geometry() self.assertEqual(point.x(), 125.0) self.assertEqual(point.y(), 10.0) self.assertEqual(features[0]['name'], "Dinagat Islands") self.assertFalse(features[1].geometry().isEmpty()) self.assertEqual(features[1].geometry().wkbType(), QgsWkbTypes.Point) point = features[1].geometry().geometry() self.assertEqual(point.x(), 110.0) self.assertEqual(point.y(), 20.0) self.assertEqual(features[1]['name'], "Henry Gale Island")
def testEncodeValue(self): """ test encoding various values for use in GeoJSON strings """ self.assertEqual(QgsJSONUtils.encodeValue(NULL), 'null') self.assertEqual(QgsJSONUtils.encodeValue(5), '5') self.assertEqual(QgsJSONUtils.encodeValue(5.9), '5.9') self.assertEqual(QgsJSONUtils.encodeValue(5999999999), '5999999999') self.assertEqual(QgsJSONUtils.encodeValue('string'), '"string"') self.assertEqual(QgsJSONUtils.encodeValue('str\ning'), '"str\\ning"') self.assertEqual(QgsJSONUtils.encodeValue('str\ring'), '"str\\ring"') self.assertEqual(QgsJSONUtils.encodeValue('str\bing'), '"str\\bing"') self.assertEqual(QgsJSONUtils.encodeValue('str\ting'), '"str\\ting"') self.assertEqual(QgsJSONUtils.encodeValue('str\\ing'), '"str\\\\ing"') self.assertEqual(QgsJSONUtils.encodeValue('str\\ning'), '"str\\\\ning"') self.assertEqual(QgsJSONUtils.encodeValue('str\n\\\\ing'), '"str\\n\\\\\\\\ing"') self.assertEqual(QgsJSONUtils.encodeValue('str/ing'), '"str\\/ing"') self.assertEqual(QgsJSONUtils.encodeValue([5, 6]), '[5,6]') self.assertEqual(QgsJSONUtils.encodeValue(['a', 'b', 'c']), '["a","b","c"]') self.assertEqual(QgsJSONUtils.encodeValue(['a', 3, 'c']), '["a",3,"c"]') self.assertEqual(QgsJSONUtils.encodeValue(['a', 'c\nd']), '["a","c\\nd"]') self.assertEqual(QgsJSONUtils.encodeValue({'key': 'value', 'key2': 5}), '{"key":"value",\n"key2":5}') self.assertEqual(QgsJSONUtils.encodeValue({'key': [1, 2, 3], 'key2': {'nested': 'nested\\result'}}), '{"key":[1,2,3],\n"key2":{"nested":"nested\\\\result"}}')
def testEncodeValue(self): """ test encoding various values for use in GeoJSON strings """ self.assertEqual(QgsJSONUtils.encodeValue(NULL), 'null') self.assertEqual(QgsJSONUtils.encodeValue(5), '5') self.assertEqual(QgsJSONUtils.encodeValue(5.9), '5.9') self.assertEqual(QgsJSONUtils.encodeValue(5999999999), '5999999999') self.assertEqual(QgsJSONUtils.encodeValue('string'), '"string"') self.assertEqual(QgsJSONUtils.encodeValue('str\ning'), '"str\\ning"') self.assertEqual(QgsJSONUtils.encodeValue('str\ring'), '"str\\ring"') self.assertEqual(QgsJSONUtils.encodeValue('str\bing'), '"str\\bing"') self.assertEqual(QgsJSONUtils.encodeValue('str\ting'), '"str\\ting"') self.assertEqual(QgsJSONUtils.encodeValue('str\\ing'), '"str\\\\ing"') self.assertEqual(QgsJSONUtils.encodeValue('str\\ning'), '"str\\\\ning"') self.assertEqual(QgsJSONUtils.encodeValue('str\n\\\\ing'), '"str\\n\\\\\\\\ing"') self.assertEqual(QgsJSONUtils.encodeValue('str/ing'), '"str\\/ing"') self.assertEqual(QgsJSONUtils.encodeValue([5, 6]), '[5,6]') self.assertEqual(QgsJSONUtils.encodeValue(['a', 'b', 'c']), '["a","b","c"]') self.assertEqual(QgsJSONUtils.encodeValue(['a', 3, 'c']), '["a",3,"c"]') self.assertEqual(QgsJSONUtils.encodeValue(['a', 'c\nd']), '["a","c\\nd"]') # handle differences due to Qt5 version, where compact output now lacks \n enc_str = QgsJSONUtils.encodeValue({'key': 'value', 'key2': 5}) self.assertTrue(enc_str == '{"key":"value",\n"key2":5}' or enc_str == '{"key":"value","key2":5}') enc_str = QgsJSONUtils.encodeValue({ 'key': [1, 2, 3], 'key2': { 'nested': 'nested\\result' } }) self.assertTrue( enc_str == '{"key":[1,2,3],\n"key2":{"nested":"nested\\\\result"}}' or enc_str == '{"key":[1,2,3],"key2":{"nested":"nested\\\\result"}}')
def testEncodeValue(self): """ test encoding various values for use in GeoJSON strings """ self.assertEqual(QgsJSONUtils.encodeValue(NULL), "null") self.assertEqual(QgsJSONUtils.encodeValue(5), "5") self.assertEqual(QgsJSONUtils.encodeValue(5.9), "5.9") self.assertEqual(QgsJSONUtils.encodeValue(5999999999), "5999999999") self.assertEqual(QgsJSONUtils.encodeValue("string"), '"string"') self.assertEqual(QgsJSONUtils.encodeValue("str\ning"), '"str\\ning"') self.assertEqual(QgsJSONUtils.encodeValue("str\ring"), '"str\\ring"') self.assertEqual(QgsJSONUtils.encodeValue("str\bing"), '"str\\bing"') self.assertEqual(QgsJSONUtils.encodeValue("str\ting"), '"str\\ting"') self.assertEqual(QgsJSONUtils.encodeValue("str\\ing"), '"str\\\\ing"') self.assertEqual(QgsJSONUtils.encodeValue("str\\ning"), '"str\\\\ning"') self.assertEqual(QgsJSONUtils.encodeValue("str\n\\\\ing"), '"str\\n\\\\\\\\ing"') self.assertEqual(QgsJSONUtils.encodeValue("str/ing"), '"str\\/ing"') self.assertEqual(QgsJSONUtils.encodeValue([5, 6]), "[5,6]") self.assertEqual(QgsJSONUtils.encodeValue(["a", "b", "c"]), '["a","b","c"]') self.assertEqual(QgsJSONUtils.encodeValue(["a", 3, "c"]), '["a",3,"c"]') self.assertEqual(QgsJSONUtils.encodeValue(["a", "c\nd"]), '["a","c\\nd"]') self.assertEqual(QgsJSONUtils.encodeValue({"key": "value", "key2": 5}), '{"key":"value",\n"key2":5}') self.assertEqual( QgsJSONUtils.encodeValue({"key": [1, 2, 3], "key2": {"nested": "nested\\result"}}), '{"key":[1,2,3],\n"key2":{"nested":"nested\\\\result"}}', )
def __init__(self, f=None, geojson=None, datatype='polygon'): """ Can initialize with either a file, or a geojson. Note datatype is ignored unless geojson is used. """ self.isValid = False if f and not geojson: l = QgsVectorLayer(f, "calculation boundary", "ogr") log("Geom type: {}, {}".format(l.geometryType(), QGis.Polygon)) if not l.isValid(): return if l.geometryType() == QGis.Polygon: datatype = "polygon" elif l.geometryType() == QGis.Point: datatype = "point" else: QtGui.QMessageBox.critical(None, tr("Error"), tr("Failed to process area of interest - unknown geometry type:{}".format(l.geometryType()))) log("Failed to process area of interest - unknown geometry type.") return elif not f and geojson: l = QgsVectorLayer("{}?crs=epsg:4326".format(datatype), "calculation boundary", "memory") fields = QgsJSONUtils.stringToFields(json.dumps(geojson), QTextCodec.codecForName('UTF8')) features = QgsJSONUtils.stringToFeatureList(json.dumps(geojson), fields, QTextCodec.codecForName('UTF8')) ret = l.dataProvider().addFeatures(features) l.commitChanges() if not ret: QtGui.QMessageBox.critical(None, tr("Error"), tr("Failed to add geojson to temporary layer.")) log("Failed to add geojson to temporary layer.") return l.commitChanges() else: raise ValueError("Must specify file or geojson") crs_source = l.crs() crs_dest = QgsCoordinateReferenceSystem(4326) t = QgsCoordinateTransform(crs_source, crs_dest) # Transform layer to WGS84 l_wgs84 = QgsVectorLayer("{}?crs=epsg:4326".format(datatype), "calculation boundary (wgs84)", "memory") #CRS transformation feats = [] for f in l.getFeatures(): g = f.geometry() g.transform(t) f.setGeometry(g) feats.append(f) l_wgs84.dataProvider().addFeatures(feats) l_wgs84.commitChanges() if not l_wgs84.isValid(): self.layer = None log("Error transforming AOI coordinates to WGS84") return else: self.layer = l_wgs84 # Transform bounding box to WGS84 self.bounding_box_geom = QgsGeometry.fromRect(l_wgs84.extent()) # Save a geometry of the bounding box self.bounding_box_geom.transform(t) # Also save a geojson of the bounding box (needed for shipping to GEE) self.bounding_box_geojson = json.loads(self.bounding_box_geom.exportToGeoJSON()) # Check the coordinates of the bounding box are now in WGS84 (in case # no transformation was available for the chosen coordinate systems) bbox = self.bounding_box_geom.boundingBox() log("Bounding box: {}, {}, {}, {}".format(bbox.xMaximum(), bbox.xMinimum(), bbox.yMinimum(), bbox.yMinimum())) if (bbox.xMinimum() < -180) or \ (bbox.xMaximum() > 180) or \ (bbox.yMinimum() < -90) or \ (bbox.yMinimum() > 90): QtGui.QMessageBox.critical(None, tr("Error"), tr("Coordinates of area of interest could not be transformed to WGS84. Check that the projection system is defined."), None) log("Error transforming AOI coordinates to WGS84") else: self.isValid = True
from qgis.utils import iface geojson_contributors = os.path.join( os.path.dirname(QgsApplication.developersMapFilePath()), 'contributors.json' ) geojson_contributors_string = codecs.open( geojson_contributors, encoding='utf-8' ).read() layer = iface.activeLayer() # Encodes a value to a JSON string representation, adding appropriate # quotations and escaping where required. print(QgsJSONUtils.encodeValue([{"name": "George", "age": 34, "size": 1.69}])) fields = QgsFields() fields_list = [ QgsField("name", QVariant.String), QgsField("age", QVariant.Int), QgsField("size", QVariant.Double) ] for f in fields_list: fields.append(f) feature = QgsFeature(fields) feature.setGeometry(QgsGeometry.fromPoint(QgsPoint(60, 5))) feature.setAttributes(["George", 34, 1.69])