Map.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. # -*- coding: utf-8 -*-
  2. """
  3. functions to use GEE within Qgis python script
  4. """
  5. import math
  6. import ee
  7. from qgis.core import QgsCoordinateReferenceSystem, QgsCoordinateTransform, QgsProject, QgsPointXY, QgsRectangle
  8. from qgis.utils import iface
  9. from qgis.PyQt.QtCore import QEventLoop, QTimer
  10. def addLayer(eeObject, visParams=None, name=None, shown=True, opacity=1.0):
  11. """
  12. Adds a given EE object to the map as a layer.
  13. https://developers.google.com/earth-engine/api_docs#mapaddlayer
  14. Uses:
  15. >>> from ee_plugin import Map
  16. >>> Map.addLayer(.....)
  17. """
  18. from ee_plugin.utils import add_or_update_ee_layer
  19. add_or_update_ee_layer(eeObject, visParams, name, shown, opacity)
  20. def centerObject(feature, zoom=None):
  21. """
  22. Centers the map view on a given object.
  23. https://developers.google.com/earth-engine/api_docs#mapcenterobject
  24. Uses:
  25. >>> from ee_plugin import Map
  26. >>> Map.centerObject(feature)
  27. """
  28. if not hasattr(feature, 'geometry'):
  29. feature = ee.Feature(feature)
  30. if not zoom:
  31. # make sure our geometry is in geo
  32. rect = feature.geometry().transform(ee.Projection('EPSG:4326'), 1)
  33. # get coordinates
  34. coords = rect.bounds().getInfo()['coordinates'][0]
  35. xmin = coords[0][0]
  36. ymin = coords[0][1]
  37. xmax = coords[2][0]
  38. ymax = coords[2][1]
  39. # construct QGIS geometry
  40. rect = QgsRectangle(xmin, ymin, xmax, ymax)
  41. # transform rect to a crs used by current project
  42. crs_src = QgsCoordinateReferenceSystem('EPSG:4326')
  43. crs_dst = QgsCoordinateReferenceSystem(QgsProject.instance().crs())
  44. geo2proj = QgsCoordinateTransform(crs_src, crs_dst, QgsProject.instance())
  45. rect_proj = geo2proj.transform(rect)
  46. # center geometry
  47. iface.mapCanvas().zoomToFeatureExtent(rect_proj)
  48. else:
  49. # set map center to feature centroid at a specified zoom
  50. center = feature.geometry().centroid().coordinates().getInfo()
  51. setCenter(center[0], center[1], zoom)
  52. def getBounds(asGeoJSON=False):
  53. """
  54. Returns the bounds of the current map view, as a list in the format [west, south, east, north] in degrees.
  55. https://developers.google.com/earth-engine/api_docs#mapgetbounds
  56. Uses:
  57. >>> from ee_plugin import Map
  58. >>> bounds = Map.getBounds(True)
  59. >>> Map.addLayer(bounds, {}, 'bounds')
  60. """
  61. ex = iface.mapCanvas().extent()
  62. # return ex
  63. xmax = ex.xMaximum()
  64. ymax = ex.yMaximum()
  65. xmin = ex.xMinimum()
  66. ymin = ex.yMinimum()
  67. # return as [west, south, east, north]
  68. if not asGeoJSON:
  69. return [xmin, ymin, xmax, ymax]
  70. # return as geometry
  71. crs = iface.mapCanvas().mapSettings().destinationCrs().authid()
  72. return ee.Geometry.Rectangle([xmin, ymin, xmax, ymax], crs, False)
  73. def getCenter():
  74. """
  75. Returns the coordinates at the center of the map.
  76. https://developers.google.com/earth-engine/api_docs#mapgetcenter
  77. Uses:
  78. >>> from ee_plugin import Map
  79. >>> center = Map.getCenter()
  80. >>> Map.addLayer(center, { 'color': 'red' }, 'center')
  81. """
  82. center = iface.mapCanvas().center()
  83. crs = iface.mapCanvas().mapSettings().destinationCrs().authid()
  84. return ee.Geometry.Point([center.x(), center.y()], crs)
  85. def setCenter(lon, lat, zoom=None):
  86. """
  87. 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.
  88. https://developers.google.com/earth-engine/api_docs#mapsetcenter
  89. Uses:
  90. >>> from ee_plugin import Map
  91. >>> Map.setCenter(lon, lat, zoom)
  92. """
  93. # wait 100 milliseconds while load the ee image
  94. loop = QEventLoop()
  95. QTimer.singleShot(100, loop.quit)
  96. loop.exec_()
  97. ### center
  98. center_point_in = QgsPointXY(lon, lat)
  99. # convert coordinates
  100. crsSrc = QgsCoordinateReferenceSystem('EPSG:4326')
  101. crsDest = QgsCoordinateReferenceSystem(QgsProject.instance().crs())
  102. xform = QgsCoordinateTransform(crsSrc, crsDest, QgsProject.instance())
  103. # forward transformation: src -> dest
  104. center_point = xform.transform(center_point_in)
  105. iface.mapCanvas().setCenter(center_point)
  106. ### zoom
  107. if zoom is not None:
  108. # transform the zoom level to scale
  109. scale_value = 591657550.5 / 2 ** (zoom - 1)
  110. iface.mapCanvas().zoomScale(scale_value)
  111. def getScale():
  112. """
  113. Returns the approximate pixel scale of the current map view, in meters.
  114. https://developers.google.com/earth-engine/api_docs#mapgetscale
  115. Uses:
  116. >>> from ee_plugin import Map
  117. >>> print(Map.getScale())
  118. """
  119. return iface.mapCanvas().scale() / 1000
  120. def getZoom():
  121. """
  122. Returns the current zoom level of the map.
  123. https://developers.google.com/earth-engine/api_docs#mapgetzoom
  124. Note that in QGIS zoom is a floating point number
  125. Uses:
  126. >>> from ee_plugin import Map
  127. >>> print(Map.getZoom())
  128. """
  129. # from https://gis.stackexchange.com/questions/268890/get-current-zoom-level-from-qgis-map-canvas
  130. scale = iface.mapCanvas().scale()
  131. dpi = iface.mainWindow().physicalDpiX()
  132. maxScalePerPixel = 156543.04
  133. inchesPerMeter = 39.37
  134. zoom = math.log((dpi * inchesPerMeter * maxScalePerPixel / scale), 2)
  135. return zoom
  136. def setZoom(zoom):
  137. """
  138. Sets the zoom level of the map.
  139. https://developers.google.com/earth-engine/api_docs#mapsetzoom
  140. Uses:
  141. >>> from ee_plugin import Map
  142. >>> Map.setZoom(15)
  143. """
  144. center = getCenter()
  145. centerObject(ee.Feature(center), zoom)