Reading and Writing Geospatial Data

Functions that Read and Write Geospatial Data

The following table lists Mapping Toolbox™ functions that read geospatial data products and file formats and write geospatial data files. Note that the geoshow and mapshow functions and the mapview GUI can read and display both vector and raster geodata files in several formats. Click function names to see their details in the Mapping Toolbox reference documentation. The Type of Coordinates column describes whether the function returns or writes data in geographic ("geo") or projected ("map") coordinates, or as geolocated data grids (which, for the functions listed, all contain geographic coordinates). Some functions can return either geographic or map coordinates, depending on what the file being read contains; these functions do not signify what type of coordinates they return (in the case of shaperead, however, you can specify whether the structure it returns should have X and Y or Lon and Lat fields).

Function

Description

Type of Data

Type of Coordinates

arcgridread

Read a gridded data set in Arc ASCII Grid Format

raster

map

avhrrgoode

Read data products derived from the Advanced Very High Resolution Radiometer (AVHRR) and stored in the Goode Homosoline projection: Global Land Cover Classification (GLCC) or Normalized Difference Vegetation Index (NDVI)

raster

geolocated

avhrrlambert

Read AVHRR GLCC and NDVI data products stored in the Lambert Conformal Conic projection

raster

geolocated

dcwdata

Read selected data from the Digital Chart of the World (DCW)

vector

geo

dcwgaz

Search for entries in the DCW gazette

vector

geo

dcwread

Read a DCW file

vector

geo

dcwrhead

Read a DCW file header

properties

geo

demdataui

GUI for interactively selecting data from various Digital Elevation Models (DEMs)

raster

geo

dted

Read U. S. Dept. of Defense Digital Terrain Elevation Data (DTED)

raster

geo

dteds

List DTED data grid filenames for a specified latitude-longitude quadrangle

filenames

geo

egm96geoid

Read 15-minute gridded geoid heights from the EGM96 geoid model

raster

geo

etopo

Read data from ETOPO1c (1-minute), ETOPO2v2c (2-minute), ETOPO2–2001 (2-minute), or ETOPO5 (5-minute) gridded global terrain relief data sets

raster

geo

fipsname

Read Federal Image Processing Standards (FIPS) names for Topographically Integrated Geographic Encoding and Referencing (TIGER) thinned boundary files

FIPS names and identifiers

geo

geotiffinfo

Information about GeoTIFF file

properties

map

geo

geotiffread

Read GeoTIFF file

raster

map

geo

geotiffwrite

Write GeoTIFF file

raster

map

geo

getworldfilename

Derive a worldfile name from an image filename

filename

geo

map

globedem

Read Global Land One-km Base Elevation (GLOBE) 30-arc-second (1 km) Digital Elevation Model

raster

geo

globedems

List GLOBE data filenames for a specified latitude-longitude quadrangle

filenames

geo

gshhs

Read Global Self-Consistent Hierarchical High-Resolution Shoreline (GSHHS) data

vector

geo

gtopo30

Read GTOPO30 30-arc-second (1 km) global elevation data

raster

geo

gtopo30s

List GTOPO30 data filenames for a specified latitude-longitude quadrangle

filenames

geo

kmlwrite

Write vector coordinates and attributes to a file in KML format

vector points and attributes

geo

readfk5

Read data from the Fifth Fundamental Catalog of Stars

vector

astro

satbath

Read 2-minute (4 km) global topography sea floor derived by Smith and Sandwell from ship soundings and satellite bathymetry

raster

geolocated

sdtsdemread

Read U.S. Geological Survey (USGS) digital elevation model (DEM) stored in SDTS (Spatial Data Transfer Standard) format (Raster Profile)

raster

geo

map

sdtsinfo

Information about SDTS data set

properties

geo

shapeinfo

Information about the geometry and attributes of geographic features stored in a shapefile (a set of ".shp", ".shx" and ".dbf" files)

properties

geo

map

shaperead

Read geographic feature coordinates and associated attributes from a shapefile

vector

geo

map

shapewrite

Write geospatial data and associated attributes in shapefile format

vector

geo

map

tbase

Read data from the 5-minute TerrainBase global digital terrain model

raster

geo

usgs24kdem

Read USGS 1:24,000 (30 m or 10 m) digital elevation models

raster

geolocated

usgsdem

Read USGS 1:250,000 (100 m) digital elevation models

raster

map

usgsdems

List USGS digital elevation model (DEM) filenames covering a specified latitude-longitude quadrangle

filenames

map

vmap0data

Extract selected data from the Vector Map Level 0 (VMAP0) CD-ROMs

vector

geo

vmap0read

Read a VMAP0 file

vector

geo

vmap0rhead

Read VMAP0 file headers

properties

geo

vmap0ui

Activate GUI for interactively selecting VMAP0 data

vector

geo

worldfileread

Read a worldfile and return a referencing matrix

georeferencing information

geo

worldfilewrite

Export a referencing matrix into an equivalent worldfile

georeferencing information

geo

The MATLAB® environment provides many general file reading and writing functions (for example, imread, imwrite, urlread, and urlwrite) which you can use to access geospatial data you want to use with Mapping Toolbox software. For example, you can read a TIFF image with imread and its accompanying worldfile with worldfileread to import the image and construct a referencing matrix to georeference it. See the Mapping Toolbox examples "Creating a Half-Resolution Georeferenced Image""Creating a Half-Resolution Georeferenced Image" and "Georeferencing an Image to an Orthotile Base Layer""Georeferencing an Image to an Orthotile Base Layer" for examples of how you can do this.

Exporting Vector Geodata

When you want to share geodata you are working with, Mapping Toolbox functions can export it two principal formats, shapefiles and KML files. Shapefiles are binary files that can contain point, line, vector, and polygon data plus attributes. Shapefiles are widely used to exchange data between different geographic information systems. KML files are text files that can contain the same type of data, and are used mainly to upload geodata the Web. The toolbox functions shapewrite and kmlwrite export to these formats.

To format attributes, shapewrite uses an auxiliary structure called a DBF spec, which you can generate with the makedbfspec function. Similarly, you can provide attributes to kmlwrite to format as a table by providing an attribute spec, a structure you can generate using the makeattribspec function or create manually.

For examples of and additional information about reading and writing shapefiles and DBF specs, see the documentation for shapeinfo, shaperead, shapewrite, and makedbfspec. The example provided in How to Construct Geographic Data Structures also demonstrates exporting vector data using shapewrite. For information about creating KML files, see the following section.

Exporting KML Files for Viewing in Earth Browsers

Keyhole Markup Language (KML) is an XML dialect for formatting 2-D and 3-D geodata for display in "Earth browsers," such as Google Earth™ mapping service, Google Maps™ mapping service, Google Mobile™ wireless service, and NASA WorldWind. Other Web browser applications, such as Yahoo!® Pipes, also support KML either by rendering or generating files. A KML file specifies a set of features (placemarks, images, polygons, 3-D models, textual descriptions, etc.) and how they are to be displayed in browsers and applications.

Each place must at least have an address or a longitude and a latitude. Places can also have textual descriptions, including hyperlinks. KML files can also specify display styles for markers, lines and polygons, and "camera view" parameters such as tilt, heading, and altitude. You can generate placemarks in KML files for individual points and sets of points that include attributes in table form. You can include HTML markups in these tables, with or without hyperlinks, but you cannot currently control the camera view of a placemark. (However, the users of an Earth browser can generally control their views of it).

Generating a Single Placemark.  This example shows how to generate a placemark using kmlwrite by specifying the latitude and longitude that identifies a location. This example also specifies the icon used for the placemark and the text that appears in the balloon associated with the placemark.

lat =  42.299827;
lon = -71.350273;
description = sprintf('%s<br>%s</b><br>%s</b>', ...
    '3 Apple Hill Drive', 'Natick, MA. 01760', ...
    'http://www.mathworks.com');
name = 'The MathWorks, Inc.';
iconFilename = ...
    'http://www.mathworks.com/products/product_listing/images/ml_icon.gif';
iconScale = 1.0;
filename = 'MathWorks.kml';
kmlwrite(filename, lat, lon, ...
    'Description', description, 'Name', name, ...
    'Icon', iconFilename, 'IconScale', iconScale);

This code produces the following KML file.

<?xml version="1.0" encoding="utf-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
   <Document>
      <name>MathWorks</name>
      <Placemark>
         <Snippet maxLines="0"> </Snippet>
         <description>3 Apple Hill Drive&amp;lt;br&gt;Natick, MA. 01760&amp;lt;/b&gt;
                      &amp;lt;br&gt;http://www.mathworks.com&amp;lt;/b&gt;
         </description>
         <name>The MathWorks, Inc.</name>
         <Style>
            <IconStyle>
               <Icon>
                 <href>
                   http://www.mathworks.com/products/product_listing/images/ml_icon.gif
                 </href>
               </Icon>
               <scale>1</scale>
            </IconStyle>
         </Style>
         <Point>
            <coordinates>-71.350273,42.299827,0.0</coordinates>
         </Point>
      </Placemark>
   </Document>
</kml>

If you view this in an Earth Browser, notice that the text inside the placemark, "http://www.mathworks.com," was automatically rendered as a hyperlink. The Google Earth service also adds a link called "Directions". kmlwrite does not include location coordinates in placemarks. This is because it is easy for users to read out where a placemark is by mousing over it or by viewing its Properties dialog box.

Placemarks from Addresses.  This example shows how to generate a placemark using street addresses or more general addresses such as postal codes, city, state, or country names, instead of latitude and longitude information. If the viewing application is capable of looking up addresses, such placemarks can be displayed in appropriate, although possibly imprecise, locations. (Note that the Google Maps service does not support address-based placemarks.)

When you use addresses, kmlwrite creates an <address> element for each placemark rather than <point> elements containing <coordinates> elements. For example, here is code for kmlwrite that generates address-based placemarks for three cities in Australia from a cell array:

  address = {'Perth, Australia', ...
             'Melbourne, Australia', ...
             'Sydney, Australia'};
  filename = 'Australian_Cities.kml';
  kmlwrite(filename, address, 'Name', address);

The generated KML file has the following structure and content:

<?xml version="1.0" encoding="utf-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
   <Document>
      <name>Australian_Cities</name>
      <Placemark>
         <Snippet maxLines="0"> </Snippet>
         <description> </description>
         <name>Perth, Australia</name>
         <address>Perth, Australia</address>
      </Placemark>
      <Placemark>
         <Snippet maxLines="0"> </Snippet>
         <description> </description>
         <name>Melbourne, Australia</name>
         <address>Melbourne, Australia</address>
      </Placemark>
      <Placemark>
         <Snippet maxLines="0"> </Snippet>
         <description> </description>
         <name>Sydney, Australia</name>
         <address>Sydney, Australia</address>
      </Placemark>
   </Document>
</kml>

Exporting Point Geostructs to Placemarks.  This example shows how to selectively read data from shapefiles and generate a KML file that identifies all or selected attributes, which you can then view in an earth browser such as Google Earth. It also shows how to customize placemark icons and vary them according to attribute values.

The Mapping Toolbox tsunamis shapefiles contain a database of 162 tsunami (tidal wave) events reported between 1950 and 2006, described as point locations with 21 variables (including 18 attributes). You can type out the metadata file tsunamis.txt to see the definitions of all the data fields. The steps below select some of these from the shapefiles and display them as tables in exported KML placemarks.

  1. Read the tsunami shapefiles, selecting certain attributes.

    There are several ways to select attributes from shapefiles. One is to pass shaperead a cell array of attribute names in the Attributes parameter. For example, you might just want to map the maximum wave height, the suspected cause, and also show the year, location and country for each event. Set up a cell array with the corresponding attribute field names as follows, remembering that field names are case-sensitive.

    attrs = {'Max_Height','Cause','Year','Location','Country'};
    

    Since the data file uses latitude and longitude coordinates, you need to specify 'UseGeoCoords',true to ensure that shaperead returns a geostruct (having Lat and Lon fields).

    tsunamis = shaperead('tsunamis.shp','useGeoCoords',true,...
                         'Attributes',attrs);
    

    Look at the first record in the tsunamis geostruct returned by shaperead.

    tsunamis(1)
    
               Geometry: 'Point'
               Lon: 128.3000
               Lat: -3.8000
        Max_Height: 2.8000
             Cause: 'Earthquake'
              Year: 1950
          Location: 'JAVA TRENCH, INDONESIA'
           Country: 'INDONESIA'
  2. Output the tsunami data to a KML file with kmlwrite

    By default, kmlwrite outputs all attribute data in a geostruct to a KML formatted file as an HTML table containing unstyled text. When you view it, the Google Earth program supplies a default marker.

    kmlfilename = 'tsunami1.kml';
    kmlwrite(kmlfilename,tsunamis);
    
  3. View the placemarks in an earth browser. For example, you can view KML files with the Google Earth browser, which must be installed on your computer.

    For Windows, use the winopen function:

    winopen(filename)
    

    For Linux, if the filename is a partial path, use the following commands:

    cmd = 'googleearth ';
    fullfilename = fullfile(pwd, filename);   
    system([cmd fullfilename])
    

    For Mac, if the filename is a partial path, use the following commands:

    cmd = 'open -a Google\ Earth '
    fullfilename = fullfile(pwd, filename);   
    system([cmd fullfilename])
    
  4. Customize the placemark contents

    To customize the HTML table in the placemark, use the makeattribspec function. Create an attribute spec for the tsunamis geostruct and inspect it.

    attribspec = makeattribspec(tsunamis)
    
    attribspec = 
        Max_Height: [1x1 struct]
             Cause: [1x1 struct]
              Year: [1x1 struct]
          Location: [1x1 struct]
           Country: [1x1 struct]

    Format the label for Max_Height as bold text, give units information about Max_Height, and also set the other attribute labels in bold.

    attribspec.Max_Height.AttributeLabel = '<b>Maximum Height</b>';
    attribspec.Max_Height.Format = '%.1f Meters';
    attribspec.Cause.AttributeLabel = '<b>Cause</b>';
    attribspec.Year.AttributeLabel = '<b>Year</b>';
    attribspec.Year.Format = '%.0f';
    attribspec.Location.AttributeLabel = '<b>Location</b>';
    attribspec.Country.AttributeLabel = '<b>Country</b>';
    

    When you use the attribute spec, all the attributes it lists are included in the placemarks generated by kmlwrite unless you remove them from the spec manually (e.g., with rmfield).

  5. Customize the placemark icon

    You can specify your own icon using kmlwrite to use instead of the default pushpin symbol. The black-and-white bullseye icon used here is specified as URL for an icon in the Google KML library.

    iconname = ...
      'http://maps.google.com/mapfiles/kml/shapes/placemark_circle.png';
    kmlwrite(kmlfilename,tsunamis,'Description',attribspec,...
      'Name',{tsunamis.Location},'Icon',iconname,'IconScale',2);
    
  6. Vary placemark size by tsunami height

    To vary the size of placemark icons, specify an icon file and a scaling factor for every observation as vectors of names (all the same) and scale factors (all computed individually) when writing a KML file. Scale the width and height of the markers to the log of Max_Height. Scaling factors for point icons are data-dependent and can take some experimenting with to get right.

    % Create vector with log2 exponents of |Max_Height| values
    [loghgtx loghgte] = log2([tsunamis.Max_Height]);
    % Create a vector replicating the icon URL
    iconnames = cellstr(repmat(iconname,numel(tsunamis),1));
    kmlwrite(kmlfilename,tsunamis,'Description',attribspec,...
        'Name',{tsunamis.Location},'Icon',iconname,...
        'IconScale',loghgte);
    

Functions That Read and Write Files in Compressed Formats

Geospatial data, like other files, are frequently stored and transmitted in compressed or archive formats, such a tar, zip, or GNU zip. Several MATLAB functions read or write such files. All create files in a folder for which you must have write permission. Input files can exist on your host computer, reside on a local area network, or be located on the Internet (in which case they are identified using URLs).

The following table identifies MATLAB functions that you can use to read, uncompress, compress, and write archived data files, geospatial or otherwise. Click any link to read the function's documentation.

Function

Purpose

gunzip

Uncompress files in the GNU zip format

untar

Extract the contents of a tar file

unzip

Extract the contents of a zip file

gzip

Compress files into the GNU zip format

tar

Compress files into a tar file

zip

Compress files into a zip file

Use the functions gunzip, untar, and unzip to read data files specified with a URL or with path syntax. Use the functions gzip, tar, and zip to create your own compressed files and archives. This capability is useful, for example, for packaging a set of shapefiles, or a worldfile along with the data grid or image it describes, for distribution.

Was this topic helpful?