[OSGeo Africa] QGIS Field Calculator - attributes for 2 layers
Tim Sutton
tim at kartoza.com
Thu Jul 7 14:38:58 PDT 2016
Hi Zoltan
> On 07 Jul 2016, at 5:55 PM, Zoltan Szecsei <zoltans at geograph.co.za> wrote:
>
> Hi Everyone,
> Maybe someone can give me a prod in the right direction?
>
> I have two Shape files (both polygons).
> I'm trying to copy an attribute field value from B.shp into A.shp, using Lon and Lat from two of A.shp attribute fields to select the relevant polygon's attribute in B.shp.
>
> In other words:
> A.shp attribute fields are: "Name", "Longitude" and "Latitude"
> B.shp attribute field is "Name"
> Using the LatLong coords in the attribute fields of A.shp, I want to select a polygon in B.shp, and write that polygons "Name" contents into this A.shp's "Name" field.
>
> Is the field calculator up for this?
I don't think so - its not really set up for doing inter-layer references. I wrote a few lines of python that will do it though (assumes you have two layers loaded with names a and b in the layers list:
reg = QgsMapLayerRegistry.instance()
a = reg.mapLayersByName('a')[0]
b = reg.mapLayersByName('b')[0]
collection = {}
index = QgsSpatialIndex()
for f in b.getFeatures():
index.insertFeature(f)
collection[f.id()] = f
with edit(b):
for af in a.getFeatures():
p = QgsPoint(af['lon'], af['lat'])
box = QgsRectangle(p, p)
for key in index.intersects(box):
feature = collection[key]
print feature['name'], af['name'], af['lon'], af['lat']
feature['name'] = af['name']
b.updateFeature(feature)
Just paste that into the QGIS python console and it will update the name field of b with the value in a for the places where the attributes lon, lat in a intersect b.
Please test in a sandbox before trying on your production data....
Regards
Tim
> I've been trying to find ways of reference fields in separate maps (layers), but neither Google or I are winning at this.
>
> Regards, and TIA,
> Zoltan
>
>
>
>
>
> --
>
> ===========================================
> Zoltan Szecsei PrGISc [PGP0031]
> Geograph (Pty) Ltd.
> GIS and Photogrammetric Services
>
> P.O. Box 7, Muizenberg 7950, South Africa.
>
> Mobile: +27-83-6004028
> Fax: +27-86-6115323 www.geograph.co.za <http://www.geograph.co.za/>
> ===========================================
> _______________________________________________
> Africa mailing list
> Africa at lists.osgeo.org
> You can UNSUBSCRIBE at http://lists.osgeo.org/mailman/listinfo/africa
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.osgeo.org/pipermail/africa/attachments/20160707/170f2957/attachment.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 455 bytes
Desc: Message signed with OpenPGP using GPGMail
URL: <http://lists.osgeo.org/pipermail/africa/attachments/20160707/170f2957/attachment.sig>
More information about the Africa
mailing list