New answers tagged

0

When a canvas changes its extent a extentsChanged signal is emitted. When you connect this signal to a method (called slot), then you are able to run this method whenever the extent changes. To deploy this mechanism I altered your code in the following way. # Declare a global variable to hold the reference to QGIS canvas canv = None # here comes your ...


1

As mentioned in the comment, you could create a model from the Processing Toolbox but if you want to create a script, you could use the following which creates the start_lat field and updates it for each layer (comments are included which hopefully will help): # Import required module to create field from PyQt4.QtCore import QVariant # For each layer in ...


1

There are now Python modules easier to use for that, as rasterio Rasterio employs GDAL to read and writes files using GeoTIFF and many other formats. Its API uses familiar Python and SciPy interfaces and idioms like context managers, iterators, and ndarrays. Therefore from Masking raster with a polygon feature in Rasterio Cookbook import rasterio ...


1

You need to use the -dstalpha option to gdalwarp e.g.: gdalwarp -cutline INPUT.shp -crop_to_cutline -dstalpha INPUT.tif OUTPUT.tif This will add an alpha band to the output tiff which masks out the area falling outside the cutline. P.S. duplicate question


0

If you don't want to use a code block, you can go for 'False' if !String! is None else 'true'


1

Edit: I checked the help for the calculate Value tool. It says: "Variables created in ModelBuilder can be used by this tool, but variables desired for use in the expression parameter cannot be connected to the Calculate Value tool. To use them in the expression, enclose the variable name in percent signs (%). For example, if you want to divide a variable ...


0

Looks like you are missing a colon at the end of the if statement. See this page for more info: http://pro.arcgis.com/en/pro-app/tool-reference/modelbuilder-toolbox/calculate-value.htm


0

I had previously installed fiona using pip. I just reinstalled it using conda : conda install -c anaconda fiona=1.6.0 It solved my problem.


2

I completely uninstalled all the QGIS I could find on my computer and then reinstalled the 64bit version of QGIS 2.8.9 stable release. Once I had done that the plugin worked properly. I think this problem either relates to have remains of more than one verison of QGIS on the computer, or it was a 32bit issue. The plugin works perfectly and is brilliant.


3

To cut an image (tif file) by using GDAL python library, and without gdalwarp utility, you need to find row and column raster indexes of top point [p1=(minX, maxY)] and bottom point [p2=(maxX, minY)]. The formulas, based in your code, are: i1 = int((p1[0] - xOrigin) / pixelWidth) j1 = int((yOrigin - p1[1] ) / pixelHeight) i2 = int((p2[0] - xOrigin) / ...


1

The Python installation of ArcGIS is not "standard" 1) you need first to install pip 2) then in theory you can install SciPy but SciPy is not a pure Python module, it needs compilation of C files and Windows has no compiler by default. You can try the Microsoft Visual C++ Compiler for Python 2.7 or a version of Christoph Gohlke Unofficial Windows ...


0

There are two problems: 1) you import Fiona twice because GeoPandas use Fiona for reading/writing shapefiles grep -nr "fiona" *.py geocode.py:4:from fiona.crs import from_epsg geodataframe.py:259: >>> import fiona geodataframe.py:260: >>> fiona.supported_drivers geodataframe.py:269: The *kwargs* are passed to fiona....


2

You can use a combination of generate_series and window LEAD function to generate dist_from and dist_to fields and use ST_LineSubstring to cut lines at some interval (here: 1000 m). SELECT row_number() OVER() new_id, b.id, ST_LineSubstring(lin.the_geom, b.dist_from/ST_Length(lin.the_geom), LEAST(b.dist_to/ST_Length(lin.the_geom), 1)) geom FROM ( ...


1

This is one of the most common GDAL/OGR Python Gotchas: A dataset is only written to disk after it is closed. Closing a dataset happens when it goes out of scope. This can be done in a number of ways and one of the following needs to be appended to the end of your script. data_out = None data_out = "some new value" del(data_out) There are libraries ...


0

Do the files at the paths filea and fileb exist? Try: filea = r'C:/Users/claudio/workspace/test/test1/rasa.tif' fileb = r'C:/Users/claudio/workspace/test/test1/rasb.tif'


0

This was implemented in RFC59.1 in GDAL release 2.1.0. def BuildVRTOptions(options = [], resolution = None, outputBounds = None, xRes = None, yRes = None, targetAlignedPixels = None, separate = None, bandList = None, addAlpha = None, ...


1

In the spirit of your question, I too would use GeoPandas like gene said. However I'll also directly answer your question how to do this in matplotlib... Create an object to map continuous values to colors. ScalarMappable is the matplotlib class to do this, and you can give it a Normalize behavior to anchor the min and max range of the values you want to ...


2

The simple way is to use GeoPandas import geopandas as gpd # read the shapefile as a GeoDataFrame can = gpd.GeoDataFrame.from_file("CAN_adm1.shp") # The first element can.head(5) ### many data #plot the shapefile/GeoDataFrame can.plot() You can even plot a column can.plot(column='NAME_1');


3

Based on my reading of this question you should be able to do: name = "layer_name" workspace = "my_workspace" cat = Catalog(location, user,pass) resource = cat.get_resource(name, workspace=workspace) if type(resource) is geoserver.resource.Coverage: ... elif type(resource) is geoserver.resource.FeatureType: ... Or possibly: if isinstance(resource, ...


1

Just now only I find that while reading a line from a text file, \n will be there at the right end. I checked that value which was read from text file by using 'print' command. In print command, the \n is not displayed a character. Hence I confused. Now the problem has been solved by using rstrip() function.


3

The polygon is not "wrong", it's just not representing landmass It uses 1 polygon for each province. You can find polygons representing Canada's borders and land surface on GADM or DIVA-GIS


2

The PostGIS extension of PostgreSQL contains an executable (shp2pgsql) to import shapefiles (.shp) to PostgreSQL. The pgRouting extension contains functions for the routing of networks (ways), such as pgr_dijkstra(). You could either write a stored procedure to do the automation or use python to access and automate the functions.


0

Once a python script is running, changes to environment variables are no longer effective. They are set up right before runtime and the interpretor will not update them afterwards. PYTHONPATH can be updated using the method sys.path.append() and that is all. A workaround is to re-execute the script after setting up the environment. This way the interpreter ...


2

If you do this on windows, you can do this through cmd prompt and use setup tools. I have to do it on a restricted computer all the time. I just install the source setup.py files as ziggy has suggested. https://pypi.python.org/pypi/setuptools In command prompt, change your directory to the location where you have extracted the package that you want to ...


0

You can use the json or simplejson library to convert the geojson to a Python object, then loop through each LineString. For each LineString get the length of the coordinates list, subtract 2 for the end points, and add it to a running sum. Or use the JQ json processor: cat my.geojson | jq "[.geometries[].coordinates | length-2] | add" assuming you have ...


0

FME has the option of calling startup and shutdown Python scripts. It sounds like you could move the two halves of your Python inside an FME workbench along with the workbench.


1

The Python version of GRASS GIS is 2.7.x and not 3.x In Python 2.7.11 (Mac OS X) import grass.script.core core.__file__ '/Applications/GRASS-7.0.app/Contents/MacOS/etc/python/grass/script/core.pyc In Python 3.5.1 import grass.script.core Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Applications/GRASS-7....


1

After asking to 3liz team they explain me that this feature is for next release. So I will try to build real processing provider plugin but I will also try installing dev build to see if i can try this new feature.


1

Double-click your raster to access its properties then go to the Style tab as you have shown in your question. Make sure the render type is set to Singleband pseudocolor: Click Apply and OK. Make sure the raster layer is still selected and run the following code to change the min and max values: rLayer = iface.activeLayer() provider = rLayer....


1

Yes, it is possible by using a QgsFeatureRequest with 'setFilterRect' method. The argument of this method is a QgsRectangle object obtained for visible part of Map Canvas with its 'extent' method (QgsMapCanvas class). I tried out my approach with this code: layer = iface.activeLayer() mapcanvas = iface.mapCanvas() rect = mapcanvas.extent() request = ...


0

I found the answer on another thread with some minor tweaks: (Adapted from Yellowcap's answer) Make a virtual environment: virtualenv env source env/bin/activate cd env Download the GDAL package version you want, unzip it and cd into it: pip download GDAL==1.11.2 (or whichever version you want) tar -zxvf GDAL-1.11.2.tar.gz cd GDAL-1.11 According to ...


4

If you inverse the coordinates, it does not work (geopy uses (latitude,longitude) in the WGS84 crs) dublin = (53.33306,-6.24889) liverpool = ( 53.41058,-2.97794) print distance(dublin, liverpool).km 217.863019038 print(vincenty(dublin, liverpool).kilometers) 217.863019038 print(great_circle(dublin, liverpool).kilometers) 217.211596704 GEOS (...


2

From the following post: https://geonet.esri.com/thread/158172 It looks like if you change your import from: import urllib to: from urllib import * this may resolve your problem.


2

I use this export GISBASE="path_to_your GISBASE" export PYTHONPATH="${PYTHONPATH}:$GISBASE/etc/python/" export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$GISBASE/lib" export GIS_LOCK=$$ export GISRC="/path_to/.grass7/rc" Then with Python import grass.script.setup as gsetup gisbase = os.environ['GISBASE'] gisdb="path_to_your_GISDBASE" location="Geol" mapset="test"...


1

I accepted @chad's answer, but was able to use the API to put together the program I wanted. Here it is: # Draw the locations of cities on a map of the US import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap from geopy.geocoders import Nominatim import math cities = [["Chicago",10], ["Boston",10], ["New York",5], ...


0

@phloem's answer only works in cases where your raster has positive values only. For a raster myrast with both negative and positive values, try the following: Float(Int("myrast"*100 + ((myrast > 0)*2 - 1)*0.5))/100.0


0

GRASS expects the LC_ALL environment variable to be set, otherwise it issues this error. As it happens, distributions such as Ubuntu have this environment variable unset by default. So the fix is to set up this variable manually at the beginning of the script, something like: if sys.platform.startswith('linux'): os.environ['LC_ALL'] = "en_GB.UTF-8" ...


0

With Python, you could use the geopy module: >>> from geopy.geocoders import Nominatim >>> geolocator = Nominatim() >>> loc = geolocator.geocode("New York, NY") >>> loc Location((40.7305991, -73.9865811, 0.0)) You could also use something like a batch geocoder, which for inputs such as: Chicago, IL Philadelphia, PA New ...


0

Another option is to install the Anaconda Python distribution which has packages for GDAL. If you are going to be doing a lot of work using GDAL with other Python packages (scipy, pandas, scikit-learn etc.,) this might be a better option than OSGeo4W. On the other hand if you want to use Python in combination with a number of open source remote sensing and ...


1

You need to import it in this way in the header of the corresponding Python file: from qgis.core import QgsRasterBandStats If you have other classes being imported from qgis.core, you can list them: from qgis.core import class1, class2, ..., QgsRasterBandStats


0

@Luke's comment led me to the Python\Lib\site-packages\osgeo folder, and I noticed immediately that it had a directory structure that looked familiar. Two levels further in (in C:\Python27\Lib\site-packages\osgeo\data\gdal) I was looking at all the csv files that GDAL looks for in GDAL_DATA. So, I amended the PATH to include C:\Python27\Lib\site-packages\...


2

I have this function to remove a group and all his layers. I think is nearly what you want. def removeGroup(name): root = QgsProject.instance().layerTreeRoot() group = root.findGroup(name) if not group is None: for child in group.children(): dump = child.dump() id = dump.split("=")[-1].strip() ...


1

I would wrap the SearchCursor in a generator expression (i.e. min()) for both speed and succinctness. Then incorporate the minimum value from the generator expression in a da type UpdateCursor. Something like the following: import arcpy fc = r'C:\path\to\your\geodatabase.gdb\feature_class' minimum_value = min(row[0] for row in arcpy.da.SearchCursor(fc, '...


2

Projection of this kind of files is sinusoidal. For this one: ftp://ladsweb.nascom.nasa.gov/allData/6/MOD13Q1/2016/129/MOD13Q1.A2016129.h07v06.006.2016147112419.hdf the next code can access to coordinates for 256 values for subDatasets[0][0] (NDVI values). from osgeo import gdal import struct nameraster = "/home/zeito/Desktop/MOD13Q1.A2016129.h07v06....


2

Is Python a requirement? If I understand what you want, you can do this in the QGIS UI, in the raster layer properties:


7

I found this other thread which was helpful How do I set layer transparency in QGIS 2.0 with Python? It seems like there should be a shorter and more efficient way, but I tested this and it works: print 'Start' active_layer = qgis.utils.iface.mapCanvas().currentLayer() raster_transparency = active_layer.renderer().rasterTransparency() ltr = ...


0

Why not sort the table ascending, then use a search cursor to grab the value for the first row? http://pro.arcgis.com/en/pro-app/tool-reference/data-management/sort.htm import arcpy workspace = r'workspace\file\path' arcpy.env.workspace = workspace input = "input_data" sort_table = "sort_table" sort_field = "your field" arcpy.Sort_management (input, ...


1

You can also use numpy in cases like this, although it will be more memory intensive. You'll still get a bottle neck when loading the data to a numpy array and then back to the datasource again, but I've found that the performance difference is better (in numpy's favor) with larger data sources, especially if you need multiple statistics/calculations.: ...


1

As @crmackey points out, the slow portion is probably due to the calculate field method. As an alternative to the other suitable solutions, and assuming you are using a geodatabase to store your data, you could use the Order By sql command to sort in ascending order before doing the update cursor. start = 0 Xfield = "XKoordInt" minValue = None wc = "%s IS ...


0

In your loop you have two function references which are revaluated for each iteration. for row in cursor: ListVal.append(row.getValue(Xfield)) It should be faster(but a bit more complex) to have the references outside of the loop: getvalue = row.getValue append = ListVal.append for row in cursor: append(getvalue(Xfield))



Top 50 recent answers are included