Visualizing data on a globe

Ever since the release of Google Earth, spinning globe applications have become a useful and popular method of geographic exploration. QGIS has an experimental plugin called QGIS Globe, which is similar to Google Earth; however, it is extremely unstable. In this recipe, we'll display a layer in Google Earth.

Getting ready

You will need to use the QGIS Plugin Manager to install the MMQGIS plugin.

Make sure you have Google Earth installed from https://www.google.com/earth/.

You will also need the following dataset from a previous recipe. It is a zipped directory called ufo which you should uncompress to your qgis_data directory:

https://geospatialpython.googlecode.com/svn/ufo.zip

How to do it...

We will load our layer and set up the attribute we want to use for the Google Earth KML output as the descriptor. We'll use the MMQIGS plugin to output our layer to KML. Finally, we'll use a cross-platform technique to open the file, which will trigger it to open in Google Earth. To do this, we need to perform the following steps:

  1. First, we will import the relevant Python libraries including the plugin. We will use the Python webbrowser module to launch Google Earth:
    from mmqgis import mmqgis_library as mmqgis
    import webbrowser
    import os
    
  2. Now, we'll load the layer:
    pth = "/Users/joellawhead/qgis_data/continental-us"
    lyrName = "continental-us"
    lyr = QgsVectorLayer(pth, lyrName, "ogr")
    
  3. Next, we'll set the output path for the KML:
    output = "/Users/joellawhead/qgis_data/us.kml"
    
  4. Then, we'll set up the variables needed by the plugin for the KML output which make up the layer identifier:
    nameAttr = "FIPS_CNTRY"
    desc = ["CNTRY_NAME",]
    sep = "Paragraph"
    
  5. Now, we can use the plugin to create the KML:
    mmqgis.mmqgis_kml_export(iface, lyrName, nameAttr, desc, 
    sep, output, False)
    
  6. Finally, we'll use the webbrowser module to open the KML file, which will default to opening in Google Earth. We need to add the file protocol at the beginning of our output for the webbrowser module to work:
    webbrowser.open("file://" + output)
    

How it works...

The MMQGIS plugin does a good job with custom scripts and has easy-to-use functions. While our method for automatically launching Google Earth may not work in every possible case, it is almost perfect.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset