Python qgis.core.QgsPointXY() Examples
The following are 23
code examples of qgis.core.QgsPointXY().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
qgis.core
, or try the search function
.
Example #1
Source File: Map.py From qgis-earthengine-plugin with MIT License | 8 votes |
def setCenter(lon, lat, zoom=None): """ Centers the map view at the given coordinates with the given zoom level. If no zoom level is provided, it uses the most recent zoom level on the map. https://developers.google.com/earth-engine/api_docs#map.setcenter Uses: >>> from ee_plugin import Map >>> Map.setCenter(lon, lat, zoom) """ ### center center_point_in = QgsPointXY(lon, lat) # convert coordinates crsSrc = QgsCoordinateReferenceSystem(4326) # WGS84 crsDest = QgsCoordinateReferenceSystem(QgsProject.instance().crs()) xform = QgsCoordinateTransform(crsSrc, crsDest, QgsProject.instance()) # forward transformation: src -> dest center_point = xform.transform(center_point_in) iface.mapCanvas().setCenter(center_point) ### zoom if zoom is not None: # transform the zoom level to scale scale_value = 591657550.5 / 2 ** (zoom - 1) iface.mapCanvas().zoomScale(scale_value)
Example #2
Source File: latLonTools.py From qgis-latlontools-plugin with GNU General Public License v2.0 | 7 votes |
def zoomTo(self, srcCrs, lat, lon): canvasCrs = self.canvas.mapSettings().destinationCrs() transform = QgsCoordinateTransform(srcCrs, canvasCrs, QgsProject.instance()) x, y = transform.transform(float(lon), float(lat)) rect = QgsRectangle(x, y, x, y) self.canvas.setExtent(rect) pt = QgsPointXY(x, y) self.highlight(pt) self.canvas.refresh() return pt
Example #3
Source File: shapeTool.py From DsgTools with GNU General Public License v2.0 | 7 votes |
def showCircle(self, startPoint): """ Draws a circle in the canvas """ nPoints = 50 x = startPoint.x() y = startPoint.y() if self.type == self.tr('distance'): r = self.param self.rubberBand.reset(QgsWkbTypes.PolygonGeometry) for itheta in range(nPoints+1): theta = itheta*(2.0*pi/nPoints) self.rubberBand.addPoint(QgsPointXY(x+r*cos(theta), y+r*sin(theta))) self.rubberBand.show() else: r = sqrt(self.param/pi) self.rubberBand.reset(QgsWkbTypes.PolygonGeometry) for itheta in range(nPoints+1): theta = itheta*(2.0*pi/nPoints) self.rubberBand.addPoint(QgsPointXY(x+r*cos(theta), y+r*sin(theta))) self.rubberBand.show()
Example #4
Source File: utils.py From qgis-shapetools-plugin with GNU General Public License v2.0 | 7 votes |
def GCgetPointsOnLine(lat1, lon1, lat2, lon2, minSegLength=1000.0, maxNodes=500): '''Get points along a great circle line between the two coordinates. minSegLength is the minimum segment length in meters before a new node point is created. maxNodes is the maximum number of points on the line to create.''' dist = GCdistanceTo(lat1, lon1, lat2, lon2) numPoints = int(dist / minSegLength) if numPoints > maxNodes: numPoints = maxNodes pts = [QgsPointXY(lon1, lat1)] f = 1.0 / (numPoints - 1.0) i = 1 while i < numPoints - 1: newlat, newlon = GCintermediatePointTo(lat1, lon1, lat2, lon2, f * i) pts.append(QgsPointXY(newlon, newlat)) i += 1 pts.append(QgsPointXY(lon2, lat2)) return pts
Example #5
Source File: utils.py From qgis-earthengine-plugin with MIT License | 7 votes |
def geom_to_geo(geom): crs_src = QgsCoordinateReferenceSystem(QgsProject.instance().crs()) crs_dst = QgsCoordinateReferenceSystem(4326) proj2geo = QgsCoordinateTransform(crs_src, crs_dst, QgsProject.instance()) if isinstance(geom, QgsPointXY): return proj2geo.transform(geom) elif isinstance(geom, QgsRectangle): return proj2geo.transformBoundingBox(geom) else: return geom.transform(proj2geo)
Example #6
Source File: captureCoordinate.py From qgis-latlontools-plugin with GNU General Public License v2.0 | 7 votes |
def snappoint(self, qpoint): match = self.canvas.snappingUtils().snapToMap(qpoint) if match.isValid(): if self.vertex is None: self.vertex = QgsVertexMarker(self.canvas) self.vertex.setIconSize(12) self.vertex.setPenWidth(2) self.vertex.setColor(self.snapcolor) self.vertex.setIconType(QgsVertexMarker.ICON_BOX) self.vertex.setCenter(match.point()) return (match.point()) # Returns QgsPointXY else: self.removeVertexMarker() return self.toMapCoordinates(qpoint) # QPoint input, returns QgsPointXY
Example #7
Source File: utm.py From qgis-latlontools-plugin with GNU General Public License v2.0 | 7 votes |
def utmString2Crs(utm, crs=epsg4326): parts = re.split(r'[\s]+', utm.upper()) utmlen = len(parts) if utmlen == 3: m = re.findall(r'(\d+)([NS])', parts[0]) if len(m) != 1 or len(m[0]) != 2: raise ValueError('Invalid UTM Coordinate') zone = int(m[0][0]) hemisphere = m[0][1] easting = float(parts[1]) northing = float(parts[2]) elif utmlen == 4: if parts[1] != 'N' and parts[1] != 'S': raise ValueError('Invalid UTM Coordinate') zone = int(parts[0]) easting = float(parts[2]) northing = float(parts[3]) else: raise ValueError('Invalid UTM Coordinate') if zone < 1 or zone > 60: raise ValueError('Invalid UTM Coordinate') utmcrs = QgsCoordinateReferenceSystem(utm_epsg_codes['{}{}'.format(zone, hemisphere)]) pt = QgsPointXY(easting, northing) utmtrans = QgsCoordinateTransform(utmcrs, crs, QgsProject.instance()) return(utmtrans.transform(pt))
Example #8
Source File: copyLatLonTool.py From qgis-latlontools-plugin with GNU General Public License v2.0 | 7 votes |
def canvasReleaseEvent(self, event): '''Capture the coordinate when the mouse button has been released, format it, and copy it to the clipboard. pt is QgsPointXY''' pt = self.snappoint(event.originalPixelPoint()) self.removeVertexMarker() if settings.captureShowLocation: if self.marker is None: self.marker = QgsVertexMarker(self.canvas) self.marker.setIconSize(18) self.marker.setPenWidth(2) self.marker.setIconType(QgsVertexMarker.ICON_CROSS) self.marker.setCenter(pt) else: self.removeMarker() try: msg = self.formatCoord(pt, self.settings.delimiter) formatString = self.coordFormatString() if msg is not None: clipboard = QApplication.clipboard() clipboard.setText(msg) self.iface.messageBar().pushMessage("", "{} coordinate {} copied to the clipboard".format(formatString, msg), level=Qgis.Info, duration=4) except Exception as e: self.iface.messageBar().pushMessage("", "Invalid coordinate: {}".format(e), level=Qgis.Warning, duration=4)
Example #9
Source File: copyLatLonTool.py From qgis-latlontools-plugin with GNU General Public License v2.0 | 7 votes |
def snappoint(self, qpoint): match = self.canvas.snappingUtils().snapToMap(qpoint) if match.isValid(): if self.vertex is None: self.vertex = QgsVertexMarker(self.canvas) self.vertex.setIconSize(12) self.vertex.setPenWidth(2) self.vertex.setColor(self.snapcolor) self.vertex.setIconType(QgsVertexMarker.ICON_BOX) self.vertex.setCenter(match.point()) return (match.point()) # Returns QgsPointXY else: self.removeVertexMarker() return self.toMapCoordinates(qpoint) # QPoint input, returns QgsPointXY
Example #10
Source File: mgrstogeom.py From qgis-latlontools-plugin with GNU General Public License v2.0 | 7 votes |
def processAlgorithm(self, parameters, context, feedback): source = self.parameterAsSource(parameters, self.PrmInputLayer, context) mgrsfieldname = self.parameterAsString(parameters, self.PrmMgrsField, context) if not mgrsfieldname: msg = 'Select an MGRS field to process' feedback.reportError(msg) raise QgsProcessingException(msg) epsg4326 = QgsCoordinateReferenceSystem("EPSG:4326") (sink, dest_id) = self.parameterAsSink( parameters, self.PrmOutputLayer, context, source.fields(), QgsWkbTypes.Point, epsg4326) featureCount = source.featureCount() total = 100.0 / featureCount if featureCount else 0 badFeatures = 0 iterator = source.getFeatures() for cnt, feature in enumerate(iterator): if feedback.isCanceled(): break m = feature[mgrsfieldname] try: m = re.sub(r'\s+', '', str(m)) # Remove all white space lat, lon = mgrs.toWgs(m) except Exception: # traceback.print_exc() badFeatures += 1 continue f = QgsFeature() f.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(lon, lat))) f.setAttributes(feature.attributes()) sink.addFeature(f) if cnt % 100 == 0: feedback.setProgress(int(cnt * total)) if badFeatures > 0: msg = "{} out of {} features contained MGRS coordinates".format(featureCount - badFeatures, featureCount) feedback.pushInfo(msg) return {self.PrmOutputLayer: dest_id}
Example #11
Source File: map_index.py From DsgTools with GNU General Public License v2.0 | 6 votes |
def makeQgsPolygon(self, xmin, ymin, xmax, ymax): """Creating a polygon for the given coordinates """ dx = (xmax - xmin)/3 dy = (ymax - ymin)/3 polyline = [] point = QgsPointXY(xmin, ymin) polyline.append(point) point = QgsPointXY(xmin+dx, ymin) polyline.append(point) point = QgsPointXY(xmax-dx, ymin) polyline.append(point) point = QgsPointXY(xmax, ymin) polyline.append(point) point = QgsPointXY(xmax, ymin+dy) polyline.append(point) point = QgsPointXY(xmax, ymax-dy) polyline.append(point) point = QgsPointXY(xmax, ymax) polyline.append(point) point = QgsPointXY(xmax-dx, ymax) polyline.append(point) point = QgsPointXY(xmin+dx, ymax) polyline.append(point) point = QgsPointXY(xmin, ymax) polyline.append(point) point = QgsPointXY(xmin, ymax-dy) polyline.append(point) point = QgsPointXY(xmin, ymin+dy) polyline.append(point) point = QgsPointXY(xmin, ymin) polyline.append(point) qgsPolygon = QgsGeometry.fromMultiPolygonXY([[polyline]]) return qgsPolygon
Example #12
Source File: polygon.py From DsgTools with GNU General Public License v2.0 | 6 votes |
def canvasMoveEvent(self, event): if self.snapCursorRubberBand: self.snapCursorRubberBand.hide() self.snapCursorRubberBand.reset(geometryType=QgsWkbTypes.PointGeometry) self.snapCursorRubberBand = None oldPoint = QgsPointXY(event.mapPoint()) event.snapPoint() point = QgsPointXY(event.mapPoint()) if oldPoint != point: self.createSnapCursor(point) if self.rubberBand: if self.qntPoint == 1: self.distanceToolTip.canvasMoveEvent(self.geometry[0], point) geom = QgsGeometry.fromPolylineXY([self.geometry[0], point]) self.rubberBand.setToGeometry(geom, None) elif self.qntPoint >= 2: if self.free: self.distanceToolTip.canvasMoveEvent(self.geometry[-1], point) geom = QgsGeometry.fromPolygonXY([self.geometry+[QgsPointXY(point.x(), point.y())]]) self.rubberBand.setToGeometry(geom, None) else: if (self.qntPoint % 2 == 1): self.setAvoidStyleSnapRubberBand() else: self.setAllowedStyleSnapRubberBand() projectedMousePoint = self.projectPoint(self.geometry[-2], self.geometry[-1], point) self.distanceToolTip.canvasMoveEvent(self.geometry[-1], projectedMousePoint) if projectedMousePoint: geom, pf = self.completePolygon(self.geometry, projectedMousePoint) self.rubberBand.setToGeometry(geom, None) else: self.initVariable()
Example #13
Source File: circle.py From DsgTools with GNU General Public License v2.0 | 6 votes |
def canvasMoveEvent(self, event): if self.snapCursorRubberBand: self.snapCursorRubberBand.hide() self.snapCursorRubberBand.reset(geometryType=QgsWkbTypes.PointGeometry) self.snapCursorRubberBand = None oldPoint = QgsPointXY(event.mapPoint()) event.snapPoint() point = QgsPointXY(event.mapPoint()) if oldPoint != point: self.createSnapCursor(point) if self.startPoint: self.endPoint = QgsPointXY(event.mapPoint()) self.showCircle(self.startPoint, self.endPoint)
Example #14
Source File: circle.py From DsgTools with GNU General Public License v2.0 | 6 votes |
def canvasReleaseEvent(self, event): if event.button() == Qt.LeftButton: if not self.startPoint: self.startPoint = QgsPointXY(event.mapPoint()) self.rubberBand = self.getRubberBand() if event.button() == Qt.RightButton: self.endGeometry()
Example #15
Source File: acquisitionFree.py From DsgTools with GNU General Public License v2.0 | 6 votes |
def finishEdition(self, event): #Método para finalizar a aquisição event.snapPoint() point = core.QgsPointXY(event.mapPoint()) if self.getRubberBand(): self.getRubberBand().addPoint(point) if not self.getRubberBand(): return if self.getRubberBand().numberOfVertices() > 2: geom = self.getRubberBand().asGeometry() if not self.controlPressed: self.acquisitionFinished.emit(geom) else: self.doReshape(geom) self.cancelEdition()
Example #16
Source File: acquisitionFree.py From DsgTools with GNU General Public License v2.0 | 6 votes |
def canvasMoveEvent(self, event): #Método para receber os eventos canvas move do Qgis #Parâmetro de entrada: event (Evento que chamou o método) if self.getRubberBand(): endPoint = self.toMapCoordinates( event.pos() ) snapRubberBand = self.getSnapRubberBand() if not(self.getStopedState()): if snapRubberBand: snapRubberBand.hide() snapRubberBand.reset(geometryType=core.QgsWkbTypes.PointGeometry) self.setSnapRubberBand(None) oldPoint = core.QgsPointXY(event.mapPoint()) event.snapPoint() point = core.QgsPointXY(event.mapPoint()) if oldPoint != point: self.createSnapCursor(point) if self.getRubberBand(): if self.contadorVert == 0: self.getRubberBand().addPoint(point) self.contadorVert+=1 else: self.getRubberBand().addPoint(oldPoint) if self.getRubberBandToStopState(): self.updateRubberBandToStopState( self.toMapCoordinates( event.pos() ) )
Example #17
Source File: acquisitionFree.py From DsgTools with GNU General Public License v2.0 | 6 votes |
def startEdition(self, event): #Método para iniciar a aquisição #Parâmetro de entrada: event (Evento) event.snapPoint() snapRubberBand = self.getSnapRubberBand() if snapRubberBand: snapRubberBand.reset(geometryType=core.QgsWkbTypes.PointGeometry) snapRubberBand.hide() self.setSnapRubberBand(None) pointMap = core.QgsPointXY(event.mapPoint()) layer = self.getCanvas().currentLayer() if layer: self.startRubberBand(pointMap, layer)
Example #18
Source File: shapeTool.py From DsgTools with GNU General Public License v2.0 | 6 votes |
def showRect(self, startPoint, param, rotAngle=0): """ Draws a rectangle in the canvas """ self.rubberBand.reset(QgsWkbTypes.PolygonGeometry) x = startPoint.x() # center point x y = startPoint.y() # center point y # rotation angle is always applied in reference to center point # to avoid unnecessary calculations c = cos(rotAngle) s = sin(rotAngle) # translating coordinate system to rubberband centroid point1 = QgsPointXY((- param), (- param)) point2 = QgsPointXY((- param), ( param)) point3 = QgsPointXY((param), ( param)) point4 = QgsPointXY((param), (- param)) # rotating and moving to original coord. sys. point1_ = QgsPointXY(point1.x()*c - point1.y()*s + x, point1.y()*c + point1.x()*s + y) point2_ = QgsPointXY(point2.x()*c - point2.y()*s + x, point2.y()*c + point2.x()*s + y) point3_ = QgsPointXY(point3.x()*c - point3.y()*s + x, point3.y()*c + point3.x()*s + y) point4_ = QgsPointXY(point4.x()*c - point4.y()*s + x, point4.y()*c + point4.x()*s + y) self.rubberBand.addPoint(point1_, False) self.rubberBand.addPoint(point2_, False) self.rubberBand.addPoint(point3_, False) self.rubberBand.addPoint(point4_, True) self.rubberBand.show() self.currentCentroid = startPoint
Example #19
Source File: utils.py From qgis-shapetools-plugin with GNU General Public License v2.0 | 6 votes |
def checkIdlCrossings(pts): outseg = [] ptlen = len(pts) pts2 = [pts[0]] for i in range(1, ptlen): if pts[i - 1].x() < -120 and pts[i].x() > 120: # We have crossed the date line going west ld = geod.Inverse(pts[i - 1].y(), pts[i - 1].x(), pts[i].y(), pts[i].x()) try: (intrlat, intrlon) = intersection_point(-89, -180, 0, pts[i - 1].y(), pts[i - 1].x(), ld['azi1']) ptnew = QgsPointXY(-180, intrlat) pts2.append(ptnew) outseg.append(pts2) ptnew = QgsPointXY(180, intrlat) pts2 = [ptnew] except Exception: pts2.append(pts[i]) if pts[i - 1].x() > 120 and pts[i].x() < -120: # We have crossed the date line going east ld = geod.Inverse(pts[i - 1].y(), pts[i - 1].x(), pts[i].y(), pts[i].x()) try: (intrlat, intrlon) = intersection_point(-89, 180, 0, pts[i - 1].y(), pts[i - 1].x(), ld['azi1']) ptnew = QgsPointXY(180, intrlat) pts2.append(ptnew) outseg.append(pts2) ptnew = QgsPointXY(-180, intrlat) pts2 = [ptnew] except Exception: pts2.append(pts[i]) else: pts2.append(pts[i]) outseg.append(pts2) return(outseg)
Example #20
Source File: mapillary_image_info.py From go2mapillary with GNU General Public License v3.0 | 6 votes |
def panToAction(self): crsCanvas = self.module.iface.mapCanvas().mapSettings().destinationCrs() # get current crs crsWGS84 = QgsCoordinateReferenceSystem(4326) # WGS 84 xform = QgsCoordinateTransform(crsWGS84, crsCanvas, QgsProject.instance()) sourcePoint = QgsPointXY(float(self.field_longitude.text()),float(self.field_latitude.text())) self.module.iface.mapCanvas().setCenter(xform.transform(sourcePoint)) self.module.iface.mapCanvas().refresh()
Example #21
Source File: captureCoordinate.py From qgis-latlontools-plugin with GNU General Public License v2.0 | 6 votes |
def canvasReleaseEvent(self, event): '''Capture the coordinate when the mouse button has been released, format it, and copy it to the clipboard. pt is QgsPointXY''' pt = self.snappoint(event.originalPixelPoint()) self.removeVertexMarker() try: canvasCRS = self.canvas.mapSettings().destinationCrs() transform = QgsCoordinateTransform(canvasCRS, epsg4326, QgsProject.instance()) pt4326 = transform.transform(pt.x(), pt.y()) self.capturePoint.emit(pt4326) except Exception as e: pass
Example #22
Source File: QgsVideo.py From QGISFMV with GNU General Public License v3.0 | 5 votes |
def mouseReleaseEvent(self, _): """ @type event: QMouseEvent @param event: @return: """ # Prevent draw on video if not started or finished if self.parent.player.position() == 0: return # Censure Draw Interaction if self._interaction.censure: geom = self.Censure_RubberBand.geometry() self.Censure_RubberBand.hide() self.drawCesure.append([geom]) # Object Tracking Interaction if self._interaction.objectTracking: geom = self.Tracking_Video_RubberBand.geometry() offset = self.surface.videoRect() bbox = (geom.x() - offset.x(), geom.y() - offset.y(), geom.width(), geom.height()) img = self.currentFrame() frame = convertQImageToMat(img) # Remo rubberband on canvas and video self.Tracking_Video_RubberBand.hide() self.Track_Canvas_RubberBand.reset() self.tracker = TrackerMOSSE_create() result = resize(frame, (offset.width(), offset.height())) try: ok = self.tracker.init(result, bbox) except Exception: return if ok: self._isinit = True # Get Traker center xc = bbox[0] + (geom.width() / 2) yc = bbox[1] + (geom.height() / 2) p = QPoint(xc, yc) Longitude, Latitude, _ = vut.GetPointCommonCoords( p, self.surface) # Draw Rubber Band on canvas self.Track_Canvas_RubberBand.addPoint(QgsPointXY(Longitude, Latitude)) else: self._isinit = False
Example #23
Source File: Qneat3Framework.py From QNEAT3 with GNU General Public License v3.0 | 5 votes |
def calcIsoContours(self, max_dist, interval, interpolation_raster_path): featurelist = [] try: import matplotlib.pyplot as plt except: return featurelist ds_in = gdal.Open(interpolation_raster_path) band_in = ds_in.GetRasterBand(1) xsize_in = band_in.XSize ysize_in = band_in.YSize geotransform_in = ds_in.GetGeoTransform() srs = osr.SpatialReference() srs.ImportFromWkt( ds_in.GetProjectionRef() ) raster_values = band_in.ReadAsArray(0, 0, xsize_in, ysize_in) raster_values[raster_values < 0] = max_dist + 1000 #necessary to produce rectangular array from raster #nodata values get replaced by the maximum value + 1 x_pos = linspace(geotransform_in[0], geotransform_in[0] + geotransform_in[1] * raster_values.shape[1], raster_values.shape[1]) y_pos = linspace(geotransform_in[3], geotransform_in[3] + geotransform_in[5] * raster_values.shape[0], raster_values.shape[0]) x_grid, y_grid = meshgrid(x_pos, y_pos) start = interval end = interval * ceil(max_dist/interval) +interval levels = arange(start, end, interval) fid = 0 for current_level in nditer(levels): self.feedback.pushInfo("[QNEAT3Network][calcIsoContours] Calculating {}-level contours".format(current_level)) contours = plt.contourf(x_grid, y_grid, raster_values, [0, current_level], antialiased=True) for collection in contours.collections: for contour_paths in collection.get_paths(): for polygon in contour_paths.to_polygons(): x = polygon[:,0] y = polygon[:,1] polylinexy_list = [QgsPointXY(i[0], i[1]) for i in zip(x,y)] feat = QgsFeature() fields = QgsFields() fields.append(QgsField('id', QVariant.Int, '', 254, 0)) fields.append(QgsField('cost_level', QVariant.Double, '', 20, 7)) feat.setFields(fields) geom = QgsGeometry().fromPolylineXY(polylinexy_list) feat.setGeometry(geom) feat['id'] = fid feat['cost_level'] = float(current_level) featurelist.insert(0, feat) fid=fid+1 return featurelist