本文整理汇总了Python中qgis.core.QgsJsonUtils类的典型用法代码示例。如果您正苦于以下问题:Python QgsJsonUtils类的具体用法?Python QgsJsonUtils怎么用?Python QgsJsonUtils使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了QgsJsonUtils类的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: testStringToFields
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)
开发者ID:,项目名称:,代码行数:18,代码来源:
示例2: testStringToFeatureList
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().isNull())
self.assertEqual(features[0].geometry().wkbType(), QgsWkbTypes.Point)
point = features[0].geometry().constGet()
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().isNull())
self.assertEqual(features[0].geometry().wkbType(), QgsWkbTypes.Point)
point = features[0].geometry().constGet()
self.assertEqual(point.x(), 125.0)
self.assertEqual(point.y(), 10.0)
self.assertEqual(features[0]['name'], "Dinagat Islands")
self.assertFalse(features[1].geometry().isNull())
self.assertEqual(features[1].geometry().wkbType(), QgsWkbTypes.Point)
point = features[1].geometry().constGet()
self.assertEqual(point.x(), 110.0)
self.assertEqual(point.y(), 20.0)
self.assertEqual(features[1]['name'], "Henry Gale Island")
开发者ID:,项目名称:,代码行数:39,代码来源:
示例3: testExportAttributes
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(QgsPoint(5, 6)))
feature.setAttributes(['Valsier Peninsula', 6.8, 198])
expected = """{"name":"Valsier Peninsula",
"cost":6.8,
"population":198}"""
self.assertEqual(QgsJsonUtils.exportAttributes(feature), expected)
# test using field formatters
source = QgsVectorLayer("Point?field=fldtxt:string&field=fldint:integer",
"parent", "memory")
pf1 = QgsFeature()
pf1.setFields(source.fields())
pf1.setAttributes(["test1", 1])
setup = QgsEditorWidgetSetup('ValueMap', {"map": {"one": 1, "two": 2, "three": 3}})
source.setEditorWidgetSetup(1, setup)
expected = """{"fldtxt":"test1",
"fldint":"one"}"""
self.assertEqual(QgsJsonUtils.exportAttributes(pf1, source), expected)
开发者ID:,项目名称:,代码行数:36,代码来源:
示例4: testEncodeValue
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"}}')
开发者ID:,项目名称:,代码行数:24,代码来源:
示例5: addFeature
def addFeature(self):
text = self.lineEdit.text().strip()
if text == "":
return
layer = self.iface.activeLayer()
if layer == None:
return
try:
if (self.inputProjection == 0) or (text[0] == '{'):
# If this is GeoJson it does not matter what inputProjection is
if text[0] == '{': # This may be a GeoJSON point
codec = QTextCodec.codecForName("UTF-8")
fields = QgsJsonUtils.stringToFields(text, codec)
fet = QgsJsonUtils.stringToFeatureList(text, fields, codec)
if (len(fet) == 0) or not fet[0].isValid():
raise ValueError('Invalid Coordinates')
geom = fet[0].geometry()
if geom.isEmpty() or (geom.wkbType() != QgsWkbTypes.Point):
raise ValueError('Invalid GeoJSON Geometry')
pt = geom.asPoint()
lat = pt.y()
lon = pt.x()
elif re.search(r'POINT\(', text) != None:
m = re.findall(r'POINT\(\s*([+-]?\d*\.?\d*)\s+([+-]?\d*\.?\d*)', text)
if len(m) != 1:
raise ValueError('Invalid Coordinates')
lon = float(m[0][0])
lat = float(m[0][1])
else:
lat, lon = LatLon.parseDMSString(text, self.inputXYOrder)
srcCrs = epsg4326
elif self.inputProjection == 1:
# This is an MGRS coordinate
text = re.sub(r'\s+', '', unicode(text)) # Remove all white space
lat, lon = mgrs.toWgs(text)
srcCrs = epsg4326
elif self.inputProjection == 4:
text = text.strip()
coord = olc.decode(text)
lat = coord.latitudeCenter
lon = coord.longitudeCenter
srcCrs = epsg4326
else: # Is either the project or custom CRS
if re.search(r'POINT\(', text) == None:
coords = re.split(r'[\s,;:]+', text, 1)
if len(coords) < 2:
raise ValueError('Invalid Coordinates')
if self.inputXYOrder == 0: # Y, X Order
lat = float(coords[0])
lon = float(coords[1])
else:
lon = float(coords[0])
lat = float(coords[1])
else:
m = re.findall(r'POINT\(\s*([+-]?\d*\.?\d*)\s+([+-]?\d*\.?\d*)', text)
if len(m) != 1:
raise ValueError('Invalid Coordinates')
lon = float(m[0][0])
lat = float(m[0][1])
if self.inputProjection == 2: # Project CRS
srcCrs = self.canvas.mapSettings().destinationCrs()
else:
srcCrs = QgsCoordinateReferenceSystem(self.inputCustomCRS)
except:
#traceback.print_exc()
self.iface.messageBar().pushMessage("", "Invalid Coordinate" , level=Qgis.Warning, duration=2)
return
self.lineEdit.clear()
caps = layer.dataProvider().capabilities()
if caps & QgsVectorDataProvider.AddFeatures:
destCRS = layer.crs() # Get the CRS of the layer we are adding a point toWgs
transform = QgsCoordinateTransform(srcCrs, destCRS, QgsProject.instance())
# Transform the input coordinate projection to the layer CRS
x, y = transform.transform(float(lon), float(lat))
feat = QgsFeature(layer.fields())
feat.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(x, y)))
if layer.fields().count() == 0:
layer.addFeature(feat)
self.lltools.zoomTo(srcCrs, lat, lon)
else:
if self.iface.openFeatureForm(layer, feat):
layer.addFeature(feat)
self.lltools.zoomTo(srcCrs, lat, lon)
开发者ID:NationalSecurityAgency,项目名称:qgis-latlontools-plugin,代码行数:84,代码来源:digitizer.py
注:本文中的qgis.core.QgsJsonUtils类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论