Following QGIS Python Programming Cookbook to create vector layer in memory?












2















I got the QGIS Python Programming Cookbook Second Edition, in hopes of improving my abilities around QGIS as well as making me confident in using Python. Keep in mind that my programming abilities are virtually nil, but I figured if I followed the directions in the book I could at least begin to grasp the basics.



Well, the first real exercise has me landing straight on my face! In it, you are supposed to create a vector layer in memory to display a point. The following is the code provided:



layer =  QgsVectorLayer('Point?crs=epsg:4326', 'MyPoint' , "memory")
pr = layer.dataProvider()
pt = QgsFeature()
point1 = QgsPoint(20,20)
pt.setGeometry(QgsGeometry.fromPoint(point1))
pr.addFeatures([pt])
layer.updateExtents()
QgsMapLayerRegistry.instance().addMapLayers([layer])


So when I enter it one line at a time, when I get to the pt.setGeometry(QgsGeometry.fromPoint(point1)) line I get the following error:




Traceback (most recent call last):
File "C:OSGEO4~1appsPython37libcode.py", line 90, in runcode
exec(code, self.locals)
File "", line 1, in
AttributeError: type object 'QgsGeometry' has no attribute 'fromPoint'




If I continue on, after inputting the last line I get the following error:




Traceback (most recent call last):
File "C:OSGEO4~1appsPython37libcode.py", line 90, in runcode
exec(code, self.locals)
File "", line 1, in
NameError: name 'QgsMapLayerRegistry' is not defined




If I run it altogether through the script editor, the first error appears. I also considered that they meant fromPointXY, but I get the following error:




Traceback (most recent call last):
File "C:OSGEO4~1appsPython37libcode.py", line 90, in runcode
exec(code, self.locals)
File "", line 1, in
TypeError: QgsGeometry.fromPointXY(): argument 1 has unexpected type 'QgsPoint'




I am out of ideas here. Since this is a book to learn PyQGIS, I that I should not be in this predicament in the first place! Either there is a major error on the FIRST exercise, or I am doing something incredibly stupid. The only other thing I can think of is that I am not using QGIS 2.18 as the book was written for, but 3.0.3 and 3.4.3 (I also tried upgrading to see if that would help, it didn't). I really don't want to downgrade just to learn PyQGIS, but if you think it would work I may just do so.



Here is a link to the page in question via Google Books










share|improve this question





























    2















    I got the QGIS Python Programming Cookbook Second Edition, in hopes of improving my abilities around QGIS as well as making me confident in using Python. Keep in mind that my programming abilities are virtually nil, but I figured if I followed the directions in the book I could at least begin to grasp the basics.



    Well, the first real exercise has me landing straight on my face! In it, you are supposed to create a vector layer in memory to display a point. The following is the code provided:



    layer =  QgsVectorLayer('Point?crs=epsg:4326', 'MyPoint' , "memory")
    pr = layer.dataProvider()
    pt = QgsFeature()
    point1 = QgsPoint(20,20)
    pt.setGeometry(QgsGeometry.fromPoint(point1))
    pr.addFeatures([pt])
    layer.updateExtents()
    QgsMapLayerRegistry.instance().addMapLayers([layer])


    So when I enter it one line at a time, when I get to the pt.setGeometry(QgsGeometry.fromPoint(point1)) line I get the following error:




    Traceback (most recent call last):
    File "C:OSGEO4~1appsPython37libcode.py", line 90, in runcode
    exec(code, self.locals)
    File "", line 1, in
    AttributeError: type object 'QgsGeometry' has no attribute 'fromPoint'




    If I continue on, after inputting the last line I get the following error:




    Traceback (most recent call last):
    File "C:OSGEO4~1appsPython37libcode.py", line 90, in runcode
    exec(code, self.locals)
    File "", line 1, in
    NameError: name 'QgsMapLayerRegistry' is not defined




    If I run it altogether through the script editor, the first error appears. I also considered that they meant fromPointXY, but I get the following error:




    Traceback (most recent call last):
    File "C:OSGEO4~1appsPython37libcode.py", line 90, in runcode
    exec(code, self.locals)
    File "", line 1, in
    TypeError: QgsGeometry.fromPointXY(): argument 1 has unexpected type 'QgsPoint'




    I am out of ideas here. Since this is a book to learn PyQGIS, I that I should not be in this predicament in the first place! Either there is a major error on the FIRST exercise, or I am doing something incredibly stupid. The only other thing I can think of is that I am not using QGIS 2.18 as the book was written for, but 3.0.3 and 3.4.3 (I also tried upgrading to see if that would help, it didn't). I really don't want to downgrade just to learn PyQGIS, but if you think it would work I may just do so.



    Here is a link to the page in question via Google Books










    share|improve this question



























      2












      2








      2








      I got the QGIS Python Programming Cookbook Second Edition, in hopes of improving my abilities around QGIS as well as making me confident in using Python. Keep in mind that my programming abilities are virtually nil, but I figured if I followed the directions in the book I could at least begin to grasp the basics.



      Well, the first real exercise has me landing straight on my face! In it, you are supposed to create a vector layer in memory to display a point. The following is the code provided:



      layer =  QgsVectorLayer('Point?crs=epsg:4326', 'MyPoint' , "memory")
      pr = layer.dataProvider()
      pt = QgsFeature()
      point1 = QgsPoint(20,20)
      pt.setGeometry(QgsGeometry.fromPoint(point1))
      pr.addFeatures([pt])
      layer.updateExtents()
      QgsMapLayerRegistry.instance().addMapLayers([layer])


      So when I enter it one line at a time, when I get to the pt.setGeometry(QgsGeometry.fromPoint(point1)) line I get the following error:




      Traceback (most recent call last):
      File "C:OSGEO4~1appsPython37libcode.py", line 90, in runcode
      exec(code, self.locals)
      File "", line 1, in
      AttributeError: type object 'QgsGeometry' has no attribute 'fromPoint'




      If I continue on, after inputting the last line I get the following error:




      Traceback (most recent call last):
      File "C:OSGEO4~1appsPython37libcode.py", line 90, in runcode
      exec(code, self.locals)
      File "", line 1, in
      NameError: name 'QgsMapLayerRegistry' is not defined




      If I run it altogether through the script editor, the first error appears. I also considered that they meant fromPointXY, but I get the following error:




      Traceback (most recent call last):
      File "C:OSGEO4~1appsPython37libcode.py", line 90, in runcode
      exec(code, self.locals)
      File "", line 1, in
      TypeError: QgsGeometry.fromPointXY(): argument 1 has unexpected type 'QgsPoint'




      I am out of ideas here. Since this is a book to learn PyQGIS, I that I should not be in this predicament in the first place! Either there is a major error on the FIRST exercise, or I am doing something incredibly stupid. The only other thing I can think of is that I am not using QGIS 2.18 as the book was written for, but 3.0.3 and 3.4.3 (I also tried upgrading to see if that would help, it didn't). I really don't want to downgrade just to learn PyQGIS, but if you think it would work I may just do so.



      Here is a link to the page in question via Google Books










      share|improve this question
















      I got the QGIS Python Programming Cookbook Second Edition, in hopes of improving my abilities around QGIS as well as making me confident in using Python. Keep in mind that my programming abilities are virtually nil, but I figured if I followed the directions in the book I could at least begin to grasp the basics.



      Well, the first real exercise has me landing straight on my face! In it, you are supposed to create a vector layer in memory to display a point. The following is the code provided:



      layer =  QgsVectorLayer('Point?crs=epsg:4326', 'MyPoint' , "memory")
      pr = layer.dataProvider()
      pt = QgsFeature()
      point1 = QgsPoint(20,20)
      pt.setGeometry(QgsGeometry.fromPoint(point1))
      pr.addFeatures([pt])
      layer.updateExtents()
      QgsMapLayerRegistry.instance().addMapLayers([layer])


      So when I enter it one line at a time, when I get to the pt.setGeometry(QgsGeometry.fromPoint(point1)) line I get the following error:




      Traceback (most recent call last):
      File "C:OSGEO4~1appsPython37libcode.py", line 90, in runcode
      exec(code, self.locals)
      File "", line 1, in
      AttributeError: type object 'QgsGeometry' has no attribute 'fromPoint'




      If I continue on, after inputting the last line I get the following error:




      Traceback (most recent call last):
      File "C:OSGEO4~1appsPython37libcode.py", line 90, in runcode
      exec(code, self.locals)
      File "", line 1, in
      NameError: name 'QgsMapLayerRegistry' is not defined




      If I run it altogether through the script editor, the first error appears. I also considered that they meant fromPointXY, but I get the following error:




      Traceback (most recent call last):
      File "C:OSGEO4~1appsPython37libcode.py", line 90, in runcode
      exec(code, self.locals)
      File "", line 1, in
      TypeError: QgsGeometry.fromPointXY(): argument 1 has unexpected type 'QgsPoint'




      I am out of ideas here. Since this is a book to learn PyQGIS, I that I should not be in this predicament in the first place! Either there is a major error on the FIRST exercise, or I am doing something incredibly stupid. The only other thing I can think of is that I am not using QGIS 2.18 as the book was written for, but 3.0.3 and 3.4.3 (I also tried upgrading to see if that would help, it didn't). I really don't want to downgrade just to learn PyQGIS, but if you think it would work I may just do so.



      Here is a link to the page in question via Google Books







      qgis python pyqgis qgsvectorlayer






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 5 hours ago









      PolyGeo

      53.3k1779238




      53.3k1779238










      asked 8 hours ago









      Benjamin SmithBenjamin Smith

      161




      161






















          4 Answers
          4






          active

          oldest

          votes


















          3














          If you are using QGIS 3 that book is outdated in hopes of improving your abilities around PyQGIS 3. Following code has 3 necessary corrections to run as expected:



          layer =  QgsVectorLayer('Point?crs=epsg:4326', 'MyPoint' , "memory")
          pr = layer.dataProvider()
          pt = QgsFeature()
          point1 = QgsPointXY(20,20) #1 correction
          pt.setGeometry(QgsGeometry.fromPointXY(point1)) #2 correction
          pr.addFeatures([pt])
          layer.updateExtents()
          QgsProject.instance().addMapLayers([layer]) #3 correction


          After running it at Python Console I got expected point layer:



          enter image description here






          share|improve this answer































            2














            You are faced with some of many incompatibilities between the APIs between QGIS 2 and 3 versions. The first issue you have already found, for the second change the last line as follows:



            layer = QgsVectorLayer('Point?crs=epsg:4326', 'MyPoint' , "memory") 
            pr = layer.dataProvider()
            pt = QgsFeature()
            point1 = QgsPoint(20,20) # or QgsPointXY(20, 20)
            pt.setGeometry(point1) # assign QgsPoint directly to QgsFeature
            # or:
            # pt.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(20, 20)))
            pr.addFeatures([pt])
            layer.updateExtents()
            QgsProject.instance().addMapLayer(layer) # API change


            For a detailed listing of API changes have a look at https://qgis.org/api/api_break.html






            share|improve this answer































              2














              You're using QGIS 2.x API in QGIS 3.x. You'll hit plenty of issues like this. You need to either:




              • use QGIS 2.18

              • wait for a third edition of the book, with updated code

              • port the code to 3.x yourself (tricky!)






              share|improve this answer































                0














                Thanks for your help everyone. As I said, I am a total noob when it comes to programming, but I didn't expect things to change so much. I guess I'll be downgrading to 2.18 in order to complete the book, as I am sure you all have better things to do than walk me through all the coding changes. Without going into my life story, one of the only things keeping me from landing a job in the GIS field is a lack of knowledge when it comes to Python. I just hope that learning on an older version won't hinder me too much.






                share|improve this answer























                  Your Answer








                  StackExchange.ready(function() {
                  var channelOptions = {
                  tags: "".split(" "),
                  id: "79"
                  };
                  initTagRenderer("".split(" "), "".split(" "), channelOptions);

                  StackExchange.using("externalEditor", function() {
                  // Have to fire editor after snippets, if snippets enabled
                  if (StackExchange.settings.snippets.snippetsEnabled) {
                  StackExchange.using("snippets", function() {
                  createEditor();
                  });
                  }
                  else {
                  createEditor();
                  }
                  });

                  function createEditor() {
                  StackExchange.prepareEditor({
                  heartbeatType: 'answer',
                  autoActivateHeartbeat: false,
                  convertImagesToLinks: false,
                  noModals: true,
                  showLowRepImageUploadWarning: true,
                  reputationToPostImages: null,
                  bindNavPrevention: true,
                  postfix: "",
                  imageUploader: {
                  brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                  contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                  allowUrls: true
                  },
                  onDemand: true,
                  discardSelector: ".discard-answer"
                  ,immediatelyShowMarkdownHelp:true
                  });


                  }
                  });














                  draft saved

                  draft discarded


















                  StackExchange.ready(
                  function () {
                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fgis.stackexchange.com%2fquestions%2f308586%2ffollowing-qgis-python-programming-cookbook-to-create-vector-layer-in-memory%23new-answer', 'question_page');
                  }
                  );

                  Post as a guest















                  Required, but never shown

























                  4 Answers
                  4






                  active

                  oldest

                  votes








                  4 Answers
                  4






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  3














                  If you are using QGIS 3 that book is outdated in hopes of improving your abilities around PyQGIS 3. Following code has 3 necessary corrections to run as expected:



                  layer =  QgsVectorLayer('Point?crs=epsg:4326', 'MyPoint' , "memory")
                  pr = layer.dataProvider()
                  pt = QgsFeature()
                  point1 = QgsPointXY(20,20) #1 correction
                  pt.setGeometry(QgsGeometry.fromPointXY(point1)) #2 correction
                  pr.addFeatures([pt])
                  layer.updateExtents()
                  QgsProject.instance().addMapLayers([layer]) #3 correction


                  After running it at Python Console I got expected point layer:



                  enter image description here






                  share|improve this answer




























                    3














                    If you are using QGIS 3 that book is outdated in hopes of improving your abilities around PyQGIS 3. Following code has 3 necessary corrections to run as expected:



                    layer =  QgsVectorLayer('Point?crs=epsg:4326', 'MyPoint' , "memory")
                    pr = layer.dataProvider()
                    pt = QgsFeature()
                    point1 = QgsPointXY(20,20) #1 correction
                    pt.setGeometry(QgsGeometry.fromPointXY(point1)) #2 correction
                    pr.addFeatures([pt])
                    layer.updateExtents()
                    QgsProject.instance().addMapLayers([layer]) #3 correction


                    After running it at Python Console I got expected point layer:



                    enter image description here






                    share|improve this answer


























                      3












                      3








                      3







                      If you are using QGIS 3 that book is outdated in hopes of improving your abilities around PyQGIS 3. Following code has 3 necessary corrections to run as expected:



                      layer =  QgsVectorLayer('Point?crs=epsg:4326', 'MyPoint' , "memory")
                      pr = layer.dataProvider()
                      pt = QgsFeature()
                      point1 = QgsPointXY(20,20) #1 correction
                      pt.setGeometry(QgsGeometry.fromPointXY(point1)) #2 correction
                      pr.addFeatures([pt])
                      layer.updateExtents()
                      QgsProject.instance().addMapLayers([layer]) #3 correction


                      After running it at Python Console I got expected point layer:



                      enter image description here






                      share|improve this answer













                      If you are using QGIS 3 that book is outdated in hopes of improving your abilities around PyQGIS 3. Following code has 3 necessary corrections to run as expected:



                      layer =  QgsVectorLayer('Point?crs=epsg:4326', 'MyPoint' , "memory")
                      pr = layer.dataProvider()
                      pt = QgsFeature()
                      point1 = QgsPointXY(20,20) #1 correction
                      pt.setGeometry(QgsGeometry.fromPointXY(point1)) #2 correction
                      pr.addFeatures([pt])
                      layer.updateExtents()
                      QgsProject.instance().addMapLayers([layer]) #3 correction


                      After running it at Python Console I got expected point layer:



                      enter image description here







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered 8 hours ago









                      xunilkxunilk

                      14k31742




                      14k31742

























                          2














                          You are faced with some of many incompatibilities between the APIs between QGIS 2 and 3 versions. The first issue you have already found, for the second change the last line as follows:



                          layer = QgsVectorLayer('Point?crs=epsg:4326', 'MyPoint' , "memory") 
                          pr = layer.dataProvider()
                          pt = QgsFeature()
                          point1 = QgsPoint(20,20) # or QgsPointXY(20, 20)
                          pt.setGeometry(point1) # assign QgsPoint directly to QgsFeature
                          # or:
                          # pt.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(20, 20)))
                          pr.addFeatures([pt])
                          layer.updateExtents()
                          QgsProject.instance().addMapLayer(layer) # API change


                          For a detailed listing of API changes have a look at https://qgis.org/api/api_break.html






                          share|improve this answer




























                            2














                            You are faced with some of many incompatibilities between the APIs between QGIS 2 and 3 versions. The first issue you have already found, for the second change the last line as follows:



                            layer = QgsVectorLayer('Point?crs=epsg:4326', 'MyPoint' , "memory") 
                            pr = layer.dataProvider()
                            pt = QgsFeature()
                            point1 = QgsPoint(20,20) # or QgsPointXY(20, 20)
                            pt.setGeometry(point1) # assign QgsPoint directly to QgsFeature
                            # or:
                            # pt.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(20, 20)))
                            pr.addFeatures([pt])
                            layer.updateExtents()
                            QgsProject.instance().addMapLayer(layer) # API change


                            For a detailed listing of API changes have a look at https://qgis.org/api/api_break.html






                            share|improve this answer


























                              2












                              2








                              2







                              You are faced with some of many incompatibilities between the APIs between QGIS 2 and 3 versions. The first issue you have already found, for the second change the last line as follows:



                              layer = QgsVectorLayer('Point?crs=epsg:4326', 'MyPoint' , "memory") 
                              pr = layer.dataProvider()
                              pt = QgsFeature()
                              point1 = QgsPoint(20,20) # or QgsPointXY(20, 20)
                              pt.setGeometry(point1) # assign QgsPoint directly to QgsFeature
                              # or:
                              # pt.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(20, 20)))
                              pr.addFeatures([pt])
                              layer.updateExtents()
                              QgsProject.instance().addMapLayer(layer) # API change


                              For a detailed listing of API changes have a look at https://qgis.org/api/api_break.html






                              share|improve this answer













                              You are faced with some of many incompatibilities between the APIs between QGIS 2 and 3 versions. The first issue you have already found, for the second change the last line as follows:



                              layer = QgsVectorLayer('Point?crs=epsg:4326', 'MyPoint' , "memory") 
                              pr = layer.dataProvider()
                              pt = QgsFeature()
                              point1 = QgsPoint(20,20) # or QgsPointXY(20, 20)
                              pt.setGeometry(point1) # assign QgsPoint directly to QgsFeature
                              # or:
                              # pt.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(20, 20)))
                              pr.addFeatures([pt])
                              layer.updateExtents()
                              QgsProject.instance().addMapLayer(layer) # API change


                              For a detailed listing of API changes have a look at https://qgis.org/api/api_break.html







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered 8 hours ago









                              DetlevDetlev

                              3,372618




                              3,372618























                                  2














                                  You're using QGIS 2.x API in QGIS 3.x. You'll hit plenty of issues like this. You need to either:




                                  • use QGIS 2.18

                                  • wait for a third edition of the book, with updated code

                                  • port the code to 3.x yourself (tricky!)






                                  share|improve this answer




























                                    2














                                    You're using QGIS 2.x API in QGIS 3.x. You'll hit plenty of issues like this. You need to either:




                                    • use QGIS 2.18

                                    • wait for a third edition of the book, with updated code

                                    • port the code to 3.x yourself (tricky!)






                                    share|improve this answer


























                                      2












                                      2








                                      2







                                      You're using QGIS 2.x API in QGIS 3.x. You'll hit plenty of issues like this. You need to either:




                                      • use QGIS 2.18

                                      • wait for a third edition of the book, with updated code

                                      • port the code to 3.x yourself (tricky!)






                                      share|improve this answer













                                      You're using QGIS 2.x API in QGIS 3.x. You'll hit plenty of issues like this. You need to either:




                                      • use QGIS 2.18

                                      • wait for a third edition of the book, with updated code

                                      • port the code to 3.x yourself (tricky!)







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered 8 hours ago









                                      ndawsonndawson

                                      18.4k22641




                                      18.4k22641























                                          0














                                          Thanks for your help everyone. As I said, I am a total noob when it comes to programming, but I didn't expect things to change so much. I guess I'll be downgrading to 2.18 in order to complete the book, as I am sure you all have better things to do than walk me through all the coding changes. Without going into my life story, one of the only things keeping me from landing a job in the GIS field is a lack of knowledge when it comes to Python. I just hope that learning on an older version won't hinder me too much.






                                          share|improve this answer




























                                            0














                                            Thanks for your help everyone. As I said, I am a total noob when it comes to programming, but I didn't expect things to change so much. I guess I'll be downgrading to 2.18 in order to complete the book, as I am sure you all have better things to do than walk me through all the coding changes. Without going into my life story, one of the only things keeping me from landing a job in the GIS field is a lack of knowledge when it comes to Python. I just hope that learning on an older version won't hinder me too much.






                                            share|improve this answer


























                                              0












                                              0








                                              0







                                              Thanks for your help everyone. As I said, I am a total noob when it comes to programming, but I didn't expect things to change so much. I guess I'll be downgrading to 2.18 in order to complete the book, as I am sure you all have better things to do than walk me through all the coding changes. Without going into my life story, one of the only things keeping me from landing a job in the GIS field is a lack of knowledge when it comes to Python. I just hope that learning on an older version won't hinder me too much.






                                              share|improve this answer













                                              Thanks for your help everyone. As I said, I am a total noob when it comes to programming, but I didn't expect things to change so much. I guess I'll be downgrading to 2.18 in order to complete the book, as I am sure you all have better things to do than walk me through all the coding changes. Without going into my life story, one of the only things keeping me from landing a job in the GIS field is a lack of knowledge when it comes to Python. I just hope that learning on an older version won't hinder me too much.







                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered 2 hours ago









                                              Benjamin SmithBenjamin Smith

                                              161




                                              161






























                                                  draft saved

                                                  draft discarded




















































                                                  Thanks for contributing an answer to Geographic Information Systems Stack Exchange!


                                                  • Please be sure to answer the question. Provide details and share your research!

                                                  But avoid



                                                  • Asking for help, clarification, or responding to other answers.

                                                  • Making statements based on opinion; back them up with references or personal experience.


                                                  To learn more, see our tips on writing great answers.




                                                  draft saved


                                                  draft discarded














                                                  StackExchange.ready(
                                                  function () {
                                                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fgis.stackexchange.com%2fquestions%2f308586%2ffollowing-qgis-python-programming-cookbook-to-create-vector-layer-in-memory%23new-answer', 'question_page');
                                                  }
                                                  );

                                                  Post as a guest















                                                  Required, but never shown





















































                                                  Required, but never shown














                                                  Required, but never shown












                                                  Required, but never shown







                                                  Required, but never shown

































                                                  Required, but never shown














                                                  Required, but never shown












                                                  Required, but never shown







                                                  Required, but never shown







                                                  Popular posts from this blog

                                                  Statuo de Libereco

                                                  Tanganjiko

                                                  Liste der Baudenkmäler in Enneberg