Mapping Toolbox 3
Users Guide
How to Contact The MathWorks
Web
Newsgroup
www.mathworks.com/contact_TS.html Technical Support
www.mathworks.com
comp.soft-sys.matlab
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
Product enhancement suggestions
Bug reports
Documentation error reports
Order status, license renewals, passcodes
Sales, pricing, and general information
508-647-7000 (Phone)
508-647-7001 (Fax)
The MathWorks, Inc.
3 Apple Hill Drive
Natick, MA 01760-2098
For contact information about worldwide offices, see the MathWorks Web site.
Mapping Toolbox Users Guide
COPYRIGHT 19972009 by The MathWorks, Inc.
The software described in this document is furnished under a license agreement. The software may be used
or copied only under the terms of the license agreement. No part of this manual may be photocopied or
reproduced in any form without prior written consent from The MathWorks, Inc.
FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentation
by, for, or through the federal government of the United States. By accepting delivery of the Program
or Documentation, the government hereby agrees that this software or documentation qualifies as
commercial computer software or commercial computer software documentation as such terms are used
or defined in FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014. Accordingly, the terms and
conditions of this Agreement and only those rights specified in this Agreement, shall pertain to and govern
the use, modification, reproduction, release, performance, display, and disclosure of the Program and
Documentation by the federal government (or other entity acquiring for or through the federal government)
and shall supersede any conflicting contractual terms or conditions. If this License fails to meet the
governments needs or is inconsistent in any respect with federal procurement law, the government agrees
to return the Program and Documentation, unused, to The MathWorks, Inc.
Trademarks
MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See
www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand
names may be trademarks or registered trademarks of their respective holders.
Patents
The MathWorks products are protected by one or more U.S. patents. Please see
www.mathworks.com/patents for more information.
Revision History
May 1997
October 1998
November 2000
July 2002
September 2003
January 2004
April 2004
June 2004
October 2004
March 2005
August 2005
September 2005
March 2006
September 2006
March 2007
September 2007
March 2008
October 2008
March 2009
September 2009
First printing
Second printing
Third printing
Online only
Online only
Online only
Online only
Fourth printing
Online only
Fifth printing
Sixth printing
Online only
Online only
Seventh printing
Online only
Eighth printing
Online only
Online only
Online only
Online only
New for Version 1.0
Version 1.1
Version 1.2 (Release 12)
Revised for Version 1.3 (Release 13)
Revised for Version 1.3.1 (Release 13SP1)
Revised for Version 2.0 (Release 13SP1+)
Revised for Version 2.0.1 (Release 13SP1+)
Revised for Version 2.0.2 (Release 14)
Revised for Version 2.0.3 (Release 14SP1)
Revised for Version 2.1 (Release 14SP2)
Minor revision for Version 2.1
Revised for Version 2.2 (Release 14SP3)
Revised for Version 2.3 (Release 2006a)
Revised for Version 2.4 (Release 2006b)
Revised for Version 2.5 (Release 2007a)
Revised for Version 2.6 (Release 2007b)
Revised for Version 2.7 (Release 2008a)
Revised for Version 2.7.1 (Release 2008b)
Revised for Version 2.7.2 (Release 2009a)
Revised for Version 3.0 (Release 2009b)
Contents
Getting Started
1
Product Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1-2
Dedication and Acknowledgment . . . . . . . . . . . . . . . . . . .
1-3
Your First Maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
See the World . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Tour Boston with the Map Viewer . . . . . . . . . . . . . . . . . . . .
1-4
1-4
1-9
Getting More Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Ways to Get Mapping Toolbox Help . . . . . . . . . . . . . . . . . . .
Consulting Release Notes . . . . . . . . . . . . . . . . . . . . . . . . . . .
1-26
1-26
1-26
Mapping Toolbox Demos and Data . . . . . . . . . . . . . . . . . .
Available Demos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Locating Geospatial Data . . . . . . . . . . . . . . . . . . . . . . . . . . .
1-28
1-28
1-29
Understanding Map Data
2
Maps and Map Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
What Is a Map? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
What Is Geospatial Data? . . . . . . . . . . . . . . . . . . . . . . . . . . .
2-2
2-2
2-2
Types of Map Data Handled by the Toolbox . . . . . . . . . .
Vector Geodata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Raster Geodata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Combining Vector and Raster Geodata . . . . . . . . . . . . . . . .
2-4
2-4
2-7
2-10
Understanding Vector Geodata . . . . . . . . . . . . . . . . . . . . .
2-13
Points, Lines, Polygons . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Segments Versus Polygons . . . . . . . . . . . . . . . . . . . . . . . . . .
Mapping Toolbox Geographic Data Structures . . . . . . . . . .
Selecting Data to Read with the shaperead Function . . . . .
2-13
2-15
2-16
2-27
Understanding Raster Geodata . . . . . . . . . . . . . . . . . . . . .
Georeferencing Raster Data . . . . . . . . . . . . . . . . . . . . . . . . .
Regular Data Grids . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Geolocated Data Grids . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2-33
2-33
2-35
2-44
Reading and Writing Geospatial Data . . . . . . . . . . . . . . .
Functions that Read and Write Geospatial Data . . . . . . . .
Exporting Vector Geodata . . . . . . . . . . . . . . . . . . . . . . . . . .
Functions That Read and Write Files in Compressed
Formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2-52
2-52
2-57
2-67
Understanding Geospatial Geometry
3
Understanding Spherical Coordinates . . . . . . . . . . . . . . .
Spheres, Spheroids, and Geoids . . . . . . . . . . . . . . . . . . . . . .
Geoid and Ellipsoid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
The Ellipsoid Vector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3-2
3-2
3-2
3-4
.............
3-11
Understanding Angles, Directions, and Distances . . . .
Positions, Azimuths, Headings, Distances, Length, and
Ranges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Working with Length and Distance Units . . . . . . . . . . . . . .
Working with Angles: Units and Representations . . . . . . .
Working with Distances on the Sphere . . . . . . . . . . . . . . . .
Angles as Binary and Formatted Numbers . . . . . . . . . . . . .
3-14
Understanding Map Projections . . . . . . . . . . . . . . . . . . . .
What Is a Map Projection? . . . . . . . . . . . . . . . . . . . . . . . . . .
Forward and Inverse Projection . . . . . . . . . . . . . . . . . . . . . .
Projection Distortions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3-29
3-29
3-30
3-30
Understanding Latitude and Longitude
vi
Contents
3-14
3-15
3-18
3-23
3-27
Great Circles, Rhumb Lines, and Small Circles . . . . . . .
Great Circles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Rhumb Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Small Circles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3-32
3-32
3-32
3-33
Directions and Areas on the Sphere and Spheroid . . . .
About Azimuths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Reckoning The Forward Problem . . . . . . . . . . . . . . . . . .
Distance, Azimuth, and Back-Azimuth (the Inverse
Problem) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Measuring Area of Spherical Quadrangles . . . . . . . . . . . . .
3-38
3-38
3-38
Planetary Almanac Data . . . . . . . . . . . . . . . . . . . . . . . . . . .
3-46
3-41
3-44
Creating and Viewing Maps
4
Introduction to Mapping Graphics . . . . . . . . . . . . . . . . . .
4-2
Using worldmap and usamap . . . . . . . . . . . . . . . . . . . . . . .
Continent, Country, Region, and State Maps Made Easy . .
Using worldmap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Using usamap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4-4
4-4
4-5
4-7
Axes for Drawing Maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
What Is a Map Axes? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Using axesm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Accessing and Manipulating Map Axes Properties . . . . . . .
Using the Map Limit Properties . . . . . . . . . . . . . . . . . . . . .
Switching Between Projections . . . . . . . . . . . . . . . . . . . . . .
Projected and Unprojected Graphic Objects . . . . . . . . . . . .
4-12
4-12
4-13
4-14
4-19
4-34
4-37
Controlling Map Frames and Grids . . . . . . . . . . . . . . . . . .
The Map Frame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
The Map Grid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4-46
4-46
4-53
Displaying Vector Data with Mapping Toolbox
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4-58
vii
Programming and Scripting Map Construction . . . . . . . . .
Displaying Vector Data as Points and Lines . . . . . . . . . . . .
Displaying Vector Maps as Lines or Patches . . . . . . . . . . . .
4-58
4-58
4-61
Displaying Data Grids . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Types of Data Grids and Raster Display Functions . . . . . .
Fitting Gridded Data to the Graticule . . . . . . . . . . . . . . . . .
Using Raster Data to Create 3-D Displays . . . . . . . . . . . . .
4-68
4-68
4-69
4-72
Interacting with Displayed Maps . . . . . . . . . . . . . . . . . . . .
Picking Locations Interactively . . . . . . . . . . . . . . . . . . . . . .
Defining Small Circles and Tracks Interactively . . . . . . . .
Working with Objects by Name . . . . . . . . . . . . . . . . . . . . . .
4-76
4-76
4-78
4-81
Making Three-Dimensional Maps
viii
Contents
Sources of Terrain Data . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Digital Terrain Elevation Data from NGA . . . . . . . . . . . . .
Digital Elevation Model Files from USGS . . . . . . . . . . . . . .
Determining What Elevation Data Exists for a Region . . .
5-2
5-2
5-3
5-3
Reading Elevation Data Interactively . . . . . . . . . . . . . . .
Extracting DEM Data with demdataui . . . . . . . . . . . . . . . .
5-13
5-13
Determining and Visualizing Visibility Across
Terrain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Computing Line of Sight with los2 . . . . . . . . . . . . . . . . . . . .
5-19
5-19
Shading and Lighting Terrain Maps . . . . . . . . . . . . . . . . .
Lighting a Terrain Map Constructed from a DTED File . .
Lighting a Global Terrain Map with lightm and
lightmui . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Surface Relief Shading . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Colored Surface Shaded Relief . . . . . . . . . . . . . . . . . . . . . . .
Relief Mapping with Light Objects . . . . . . . . . . . . . . . . . . .
5-22
5-22
Draping Data on Elevation Maps . . . . . . . . . . . . . . . . . . . .
5-40
5-25
5-29
5-33
5-36
Draping Geoid Heights over Topography . . . . . . . . . . . . . .
Draping Data over Terrain with Different Gridding . . . . .
5-40
5-43
Working with the Globe Display . . . . . . . . . . . . . . . . . . . .
What Is the Globe Display? . . . . . . . . . . . . . . . . . . . . . . . . .
The Globe Display Compared with the Orthographic
Projection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Using Opacity and Transparency in Globe Displays . . . . .
Over-the-Horizon 3-D Views Using Camera Positioning
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Displaying a Rotating Globe . . . . . . . . . . . . . . . . . . . . . . . . .
5-49
5-49
5-50
5-52
5-55
5-57
Customizing and Printing Maps
6
Inset Maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6-2
Graphic Scales . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6-8
.....................................
6-14
Thematic Maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
What Is a Thematic Map? . . . . . . . . . . . . . . . . . . . . . . . . . . .
Choropleth Maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Special Thematic Mapping Functions . . . . . . . . . . . . . . . . .
6-17
6-17
6-18
6-23
Using Cartesian MATLAB Display Functions . . . . . . . . .
Adding Graphic Objects to Map Axes . . . . . . . . . . . . . . . . .
Example 1: Triangulating Data Points . . . . . . . . . . . . . . . .
Example 2: Constructing Quiver Maps . . . . . . . . . . . . . . . .
6-28
6-28
6-28
6-30
Using Colormaps and Colorbars . . . . . . . . . . . . . . . . . . . .
Colormap for Terrain Data . . . . . . . . . . . . . . . . . . . . . . . . . .
Contour Colormaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Colormaps for Political Maps . . . . . . . . . . . . . . . . . . . . . . . .
Labeling Colorbars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Editing Colorbars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6-34
6-34
6-37
6-39
6-43
6-44
North Arrows
ix
Printing Maps to Scale . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6-45
Manipulating Geospatial Data
7
Manipulating Vector Geodata . . . . . . . . . . . . . . . . . . . . . . .
Repackaging Vector Objects . . . . . . . . . . . . . . . . . . . . . . . . .
Matching Line Segments . . . . . . . . . . . . . . . . . . . . . . . . . . .
Geographic Interpolation of Vectors . . . . . . . . . . . . . . . . . .
Vector Intersections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Polygon Area . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Overlaying Polygons with Set Logic . . . . . . . . . . . . . . . . . . .
Cutting Polygons at the Date Line . . . . . . . . . . . . . . . . . . . .
Building Buffer Zones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Trimming Vector Data to a Rectangular Region . . . . . . . . .
Trimming Vector Data to an Arbitrary Region . . . . . . . . . .
Simplifying Vector Coordinate Data . . . . . . . . . . . . . . . . . .
7-2
7-2
7-4
7-5
7-8
7-11
7-12
7-17
7-19
7-22
7-25
7-25
Manipulating Raster Geodata . . . . . . . . . . . . . . . . . . . . . . .
Vector-to-Raster Data Conversion . . . . . . . . . . . . . . . . . . . .
Data Grids as Logical Variables . . . . . . . . . . . . . . . . . . . . . .
Data Grid Values Along a Path . . . . . . . . . . . . . . . . . . . . . .
Data Grid Gradient, Slope, and Aspect . . . . . . . . . . . . . . . .
7-32
7-32
7-40
7-42
7-44
Using Map Projections and Coordinate Systems
Contents
What Is a Map Projection? . . . . . . . . . . . . . . . . . . . . . . . . . .
8-2
Quantitative Properties of Map Projections . . . . . . . . . .
8-3
The Three Main Families of Map Projections . . . . . . . . .
Unwrapping the Sphere to a Plane . . . . . . . . . . . . . . . . . . .
Cylindrical Projections . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Conic Projections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
8-5
8-5
8-5
8-7
Azimuthal Projections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
8-8
Projection Aspect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
The Orientation Vector . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
8-10
8-10
Projection Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Projection Characteristics Maps Can Have . . . . . . . . . . . . .
8-18
8-18
Visualizing and Quantifying Projection Distortions . . .
Displays of Spatial Error in Maps . . . . . . . . . . . . . . . . . . . .
Quantifying Map Distortions at Point Locations . . . . . . . .
8-27
8-27
8-31
Accessing, Computing, and Inverting Map Projection
Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Accessing Projected Coordinate Data . . . . . . . . . . . . . . . . .
Projecting Coordinates Without a Map Axes . . . . . . . . . . . .
Inverse Map Projection . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Coordinate Transformations . . . . . . . . . . . . . . . . . . . . . . . .
8-37
8-37
8-39
8-41
8-45
Working with the UTM System . . . . . . . . . . . . . . . . . . . . . .
What Is the Universal Transverse Mercator System? . . . .
Understanding UTM Parameters . . . . . . . . . . . . . . . . . . . .
Setting UTM Parameters with a GUI . . . . . . . . . . . . . . . . .
Working in UTM Without a Map Axes . . . . . . . . . . . . . . . .
Mapping Across UTM Zones . . . . . . . . . . . . . . . . . . . . . . . . .
8-51
8-51
8-52
8-54
8-59
8-60
.................
8-63
Summary and Guide to Projections
Creating Web Map Service Maps
9
Introduction to Web Map Service . . . . . . . . . . . . . . . . . . .
What Web Map Service Servers Provide . . . . . . . . . . . . . . .
Basic WMS Terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . .
9-2
9-2
9-4
Basic Workflow for Creating WMS Maps . . . . . . . . . . . . .
Workflow Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
9-5
9-5
xi
Creating a Map of Elevation in Europe . . . . . . . . . . . . . . . .
9-5
Searching the WMS Database . . . . . . . . . . . . . . . . . . . . . . .
Introduction to the WMS Database . . . . . . . . . . . . . . . . . . .
Finding Temperature Data . . . . . . . . . . . . . . . . . . . . . . . . . .
9-8
9-8
9-9
Refining Your Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Refining by Text String . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Refining by Geographic Limits . . . . . . . . . . . . . . . . . . . . . . .
9-11
9-11
9-12
..............................
9-13
Retrieving Your Map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Ways to Retrieve Your Map . . . . . . . . . . . . . . . . . . . . . . . . .
Understanding Coordinate Reference System Codes . . . . .
Retrieving Your Map with wmsread . . . . . . . . . . . . . . . . . .
Setting Optional Parameters . . . . . . . . . . . . . . . . . . . . . . . .
Retrieving Your Map with WebMapServer.getMap . . . . . .
9-15
9-15
9-15
9-16
9-17
9-19
Modifying Your Request . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Setting the Geographic Limits and Background Color . . . .
Setting the Geographic Limits, Image Dimension, Style,
and Image Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Manually Editing a URL . . . . . . . . . . . . . . . . . . . . . . . . . . .
9-22
9-22
Overlaying Multiple Layers . . . . . . . . . . . . . . . . . . . . . . . . .
Creating a Composite Map of Multiple Layers from One
Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Combining Layers from One Server with Data from Other
Sources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Draping Topography and Ortho-Imagery Layers over a
Digital Elevation Model Layer . . . . . . . . . . . . . . . . . . . . .
9-30
Animating Data Layers . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Creating Movie of Daily Planet Images for One Month . . .
Creating an Animated GIF File . . . . . . . . . . . . . . . . . . . . . .
Animating Time-Lapse Radar Observations . . . . . . . . . . . .
Displaying Animation of Radar Images over Daily Planet
Backdrop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
9-40
9-40
9-42
9-44
Updating Your Layer
xii
Contents
9-24
9-27
9-30
9-33
9-34
9-47
Saving Favorite Servers . . . . . . . . . . . . . . . . . . . . . . . . . . . .
9-50
Exploring Other Layers from a Server . . . . . . . . . . . . . . .
9-52
Writing a KML File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
9-55
Searching for Layers Outside the Database . . . . . . . . . .
9-56
Hosting Your Own WMS Server . . . . . . . . . . . . . . . . . . . . .
9-57
Common Problems with WMS Servers . . . . . . . . . . . . . . .
Connection Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Wrong Scale . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Problems with Geographic Limits . . . . . . . . . . . . . . . . . . . .
Problems with Server Changing LayerName . . . . . . . . . . .
Non-EPSG:4326 Coordinate Reference Systems . . . . . . . . .
Map Not Returned . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Unsupported WMS Version . . . . . . . . . . . . . . . . . . . . . . . . .
Other Unrecoverable Server Errors . . . . . . . . . . . . . . . . . . .
9-58
9-58
9-60
9-60
9-61
9-62
9-62
9-63
9-63
Mapping Applications
10
Geographic Statistics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Statistics for Point Locations on a Sphere . . . . . . . . . . . . . .
Geographic Means . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Geographic Standard Deviation . . . . . . . . . . . . . . . . . . . . . .
Equal-Areas in Geographic Statistics . . . . . . . . . . . . . . . . .
10-2
10-2
10-2
10-4
10-7
Navigation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
What Is Navigation? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Conventions for Navigational Functions . . . . . . . . . . . . . . .
Fixing Position . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Planning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Track Laydown Displaying Navigational Tracks . . . . . . .
Dead Reckoning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Drift Correction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Time Zones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
10-11
10-11
10-12
10-13
10-25
10-29
10-31
10-36
10-38
xiii
Function Reference
11
Geospatial Data Import and Access . . . . . . . . . . . . . . . . .
Standard File Formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Gridded Terrain and Bathymetry Products . . . . . . . . . . . .
Vector Map Products . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Miscellaneous Data Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . .
GUIs for Data Import . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
File Reading Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Ellipsoids, Radii, Areas, and Volumes . . . . . . . . . . . . . . . . .
11-2
11-2
11-3
11-4
11-5
11-5
11-5
11-5
Web Map Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
WMS Server and Layer Information . . . . . . . . . . . . . . . . . .
WMS Capabilities Information . . . . . . . . . . . . . . . . . . . . . .
WMS Map Rendering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
11-6
11-6
11-6
11-7
Vector Map Data and Geographic Data Structures . . . .
Geographic Data Structures . . . . . . . . . . . . . . . . . . . . . . . . .
Data Manipulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Utilities for NaN-Separated Polygons and Lines . . . . . . . .
11-7
11-7
11-8
11-8
Georeferenced Images and Data Grids . . . . . . . . . . . . . . .
Spatial Referencing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terrain Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Other Analysis/Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Construction and Modification . . . . . . . . . . . . . . . . . . . . . . .
Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
11-9
11-9
11-10
11-11
11-11
11-12
Map Projections and Coordinates . . . . . . . . . . . . . . . . . . .
Available Map Projections . . . . . . . . . . . . . . . . . . . . . . . . . .
Map Projection Transformations . . . . . . . . . . . . . . . . . . . . .
Map Trimming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Angles, Scales, and Distortions . . . . . . . . . . . . . . . . . . . . . .
Visualizing Map Distortions . . . . . . . . . . . . . . . . . . . . . . . . .
UTM System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Coordinate Rotation on the Sphere . . . . . . . . . . . . . . . . . . .
Trimming and Clipping . . . . . . . . . . . . . . . . . . . . . . . . . . . .
11-12
11-13
11-13
11-13
11-14
11-14
11-14
11-14
11-15
Map Display and Interaction . . . . . . . . . . . . . . . . . . . . . . . 11-15
Map Creation and High-Level Display . . . . . . . . . . . . . . . . 11-16
xiv
Contents
Vector Symbolization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Lines and Contours . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Patch Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Data Grids . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Light Objects and Lighted Surfaces . . . . . . . . . . . . . . . . . . .
Thematic Maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Map Annotation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Colormaps for Map Displays . . . . . . . . . . . . . . . . . . . . . . . .
Interactive Map Positions . . . . . . . . . . . . . . . . . . . . . . . . . . .
Interactive Track and Circle Definition . . . . . . . . . . . . . . . .
GUIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Map Object and Projection Properties . . . . . . . . . . . . . . . . .
Map Appearance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Display Clearing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
11-17
11-17
11-17
11-18
11-18
11-18
11-19
11-20
11-20
11-20
11-20
11-21
11-22
11-23
Geographic Calculations . . . . . . . . . . . . . . . . . . . . . . . . . . .
Geometry of Sphere and Ellipsoid . . . . . . . . . . . . . . . . . . . .
3-D Coordinates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Ellipsoids and Latitudes . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Geometric Object Overlay . . . . . . . . . . . . . . . . . . . . . . . . . . .
Geographic Statistics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Navigation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
11-23
11-24
11-25
11-25
11-26
11-27
11-27
Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Angle Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Conversion Factors for Angles and Distances . . . . . . . . . . .
Data Precision . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Distance Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Image Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
String Formatters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Longitude or Azimuth Wrapping . . . . . . . . . . . . . . . . . . . . .
11-28
11-29
11-29
11-29
11-30
11-30
11-30
11-30
GUIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Map Definition Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Mapping Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Display Manipulation Tools . . . . . . . . . . . . . . . . . . . . . . . . .
Object Property Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Track Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Map Data Construction Tools . . . . . . . . . . . . . . . . . . . . . . . .
11-31
11-31
11-32
11-32
11-33
11-33
11-34
xv
Functions Alphabetical List
12
Class Reference
13
Web Map Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
WebMapServer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
WMSCapabilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
WMSLayer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
WMSMapRequest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
13-2
13-2
13-2
13-2
13-3
Map Projections Reference
14
............................
14-2
Pseudocylindrical Projections . . . . . . . . . . . . . . . . . . . . . .
14-2
Conic Projections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
14-4
.............
14-4
Azimuthal, Pseudoazimuthal, and Modified Azimuthal
Projections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
14-4
UTM and UPS Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
14-5
3-D Globe Display . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
14-5
Cylindrical Projections
Polyconic and Pseudoconic Projections
xvi
Contents
Map Projections Alphabetical List
15
Glossary
Bibliography
A
Examples
B
Your First Maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
B-2
Understanding Vector Geodata . . . . . . . . . . . . . . . . . . . . .
B-2
Raster Geodata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
B-2
Combining Vector and Raster Geodata . . . . . . . . . . . . . .
B-2
........................
B-2
Geolocated Data Grids . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
B-3
Exporting Vector Geodata . . . . . . . . . . . . . . . . . . . . . . . . . .
B-3
Creating and Viewing Maps . . . . . . . . . . . . . . . . . . . . . . . .
B-3
Making Three-Dimensional Maps . . . . . . . . . . . . . . . . . . .
B-3
Understanding Raster Data
xvii
Making Three-dimensional Maps . . . . . . . . . . . . . . . . . . . .
B-4
Customizing and Printing Maps . . . . . . . . . . . . . . . . . . . . .
B-4
Using Cartesian MATLAB Display Functions . . . . . . . . .
B-4
Using Cartesian MATLAB Display Functions . . . . . . . . .
B-5
....................
B-5
Vector Data Manipulation . . . . . . . . . . . . . . . . . . . . . . . . . .
B-5
Raster Data Manipulation . . . . . . . . . . . . . . . . . . . . . . . . . .
B-5
Projections and Transformations . . . . . . . . . . . . . . . . . . .
B-6
Web Map Service Maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
B-6
Using Colormaps and Colorbars
Index
xviii
Contents
1
Getting Started
Product Overview on page 1-2
Dedication and Acknowledgment on page 1-3
Your First Maps on page 1-4
Getting More Help on page 1-26
Mapping Toolbox Demos and Data on page 1-28
Note Some cross-references in this document refer to reference
material included only in the electronic version of this users guide. The
complete users guide is available in the MATLAB Help browser,
and in HTML and PDF formats on the MathWorks Web site, at
http://www.mathworks.com/access/helpdesk/help/toolbox/map/map.html.
Getting Started
Product Overview
The Mapping Toolbox product comprises an extensive set of functions and
graphical user interfaces (GUIs) for creating map displays and analyzing
and manipulating geospatial data in the MATLAB environment. You can
create maps that combine different types of data from multiple sources and
display them in their correct spatial relationships. The toolbox supports
spatial analysis methods such as line-of-sight calculations on terrain data
and geographic computations that account for the curvature of the Earths
surface. Its library of map projections and georeferencing utilities give you
precise control over projected and unprojected coordinate systems.
Most Mapping Toolbox functions are written in the open MATLAB language.
This means that you can inspect the algorithms, adapt them to create your
own custom functions, and automate frequently performed tasks. The toolbox
also includes sample data sets, examples, and demos that illustrate key
concepts, which provide starting points for geospatial data analysis projects
of your own.
Briefly summarized, the toolbox provides functionality in the following areas:
Import and export of file-based geospatial data
Vector map data and geographic data structures
Georeferenced images and data grids
Web Map Service layer selection and map retrieval
Map projections and coordinates
Map display and interaction
Geographic calculations for vector and raster data
A map viewer and other graphical user interfaces
The sections that follow get you started using Mapping Toolbox capabilities,
and describe what its documentation and demos contain and where to look for
categories of information. For a complete classified list of Mapping Toolbox
functions and features, see Chapter 11, Function Reference.
1-2
Dedication and Acknowledgment
Dedication and Acknowledgment
In memory of John P. Snyder (192697), whose meticulous studies and
systematic descriptions of map projections inspired and enabled the creation
of Mapping Toolbox software.
This software was originally developed and maintained through Version 1.3
by Systems Planning and Analysis, Inc. (SPA), of Alexandria, Virginia.
Except where noted, the information contained in demo and sample data
files (found in toolbox/map/mapdemos) is derived from publicly available
digital data sets. These data files are provided as a convenience to Mapping
Toolboxusers. The MathWorks, Inc. makes no claims that any of this data is
free of defects or errors, or that the representations of geographic features or
names are up to date or authoritative.
1-3
Getting Started
Your First Maps
In this section...
See the World on page 1-4
Tour Boston with the Map Viewer on page 1-9
This section helps you exercise high-level functions and GUIs to explore
mapping and visualizing geodata. It explores worldmap and other functions,
and then describes how to use the Map Viewer (mapview). Run the demos
described in Mapping Toolbox Demos and Data on page 1-28 and search
the index of examples to further acquaint yourself with Mapping Toolbox
capabilities.
See the World
Spatial data is a general term that refers to data describing the location,
shape, and spatial relationships of anything, from engineering drawings
to maps of galaxies. Geospatial data is spatial data that is in some way
georeferenced, or tied to specific locations on, under, or above the surface
of a planet.
Geospatial data can be voluminous, complex, and difficult to work with.
Mapping Toolbox functions handle many of the details of loading and
displaying data for you, and has built-in data structures for representing
geospatial data. Nevertheless, the more you understand about your data and
the capabilities of the toolbox, the more interesting applications you will be
able to pursue, and the more useful their results will be to you and others.
Getting started making world maps with the toolbox is easy.
1 In the MATLAB Command Window, type
worldmap world
This creates an empty map axes, ready to hold the data of your choice.
Function worldmap automatically selected a reasonable choice for your
map projection and coordinate limits. In this case, it chooses a Robinson
projection centered on the prime meridian and the equator (0 latitude,
0 longitude).
1-4
Your First Maps
Note that if you type worldmap without an argument a list box appears from
which you can select a country, continent, or region. The worldmap function
then generates a map axes with appropriate projection and map limits.
2 Import low-resolution world coastlines stored as simple MATLAB
coordinate vectors in a MAT-file:
whos -file coast.mat
Name
Size
lat
long
9865x1
9865x1
Bytes
Class
78920
78920
double
double
Attributes
3 Load and plot the coastlines on the world map:
load coast
plotm(lat, long)
The plotm function is a geographic equivalent to the MATLAB plot
function. It accepts coordinates in latitude and longitude, which it
transforms to x and y via a specified map projection (in this case specified
by worldmap) before displaying them in a figure axes. Certain Mapping
Toolbox functions that end with m, such as plotm and textm, are modeled
after familiar MATLAB functions that handle nongeographic coordinate
data.
1-5
Getting Started
Notice how the world coastlines form distinct polygons, even though only
a single vector of latitudes and a corresponding vector of longitudes are
provided. The reason is because of NaN separators, which implicitly divide
each vector into multiple parts.
[latcells, loncells] = polysplit(lat, long);
numel(latcells)
ans =
241
lat and long include NaN terminators as well as separators, showing that
the coast data set is organized into precisely 241 polygons.
4 Now create a new map axes for plotting data over Europe, and this time
specify a return argument:
h = worldmap('Europe');
1-6
Your First Maps
For the map of the world, worldmap chose a pseudocylindrical Robinson
projection. For Europe, it chose an Equidistant Conic projection. How can
you tell which projection worldmap is using?
When you specify a return argument for worldmap and certain other
mapping functions, a handle (e.g., h) to the figures axes is returned.
The axes object on which map data is displayed is called a map axes. In
addition to the graphics properties common to any MATLAB axes object,
a map axes object contains additional properties covering map projection
type, projection parameters, map limits, etc. The getm and setm functions
and others allow you to define, access, and modify these properties.
5 To inspect the map axes properties for the map of Europe, first dereference
the handle with the getm command (which is similar to the MATLAB get
command, but returns map-specific data):
mstruct = getm(h);
6 Now you can inspect the 1-by-1 structure mstruct by listing it, using the
property editor, or by accessing any field directly. For instance, to see the
map projection selected for the map of Europe, type
mstruct.mapprojection
ans =
1-7
Getting Started
eqdconic
7 Add data to the map of Europe using the geoshow function and importing
from several shapefiles in the toolbox/map/mapdemos directory:
geoshow('landareas.shp', 'FaceColor', [0.15 0.5 0.15])
geoshow('worldlakes.shp', 'FaceColor', 'cyan')
geoshow('worldrivers.shp', 'Color', 'blue')
geoshow('worldcities.shp', 'Marker', '.',...
'MarkerEdgeColor', 'red')
Note how geoshow can plot data directly from files onto a map axes without
first loading it into the MATLAB workspace.
8 Finally, place a label on the map to identify the Mediterranean Sea.
labelLat = 35;
labelLon = 14;
textm(labelLat, labelLon, 'Mediterranean Sea')
1-8
Your First Maps
Look at the reference documentation for worldmap and experiment with its
options. To learn more about display properties for map axes and how to
control them, see Accessing and Manipulating Map Axes Properties on
page 4-14. See the reference page for geoshow to find out more about its
capabilities.
Tour Boston with the Map Viewer
The Map Viewer is an interactive tool for browsing map data. With it you can
assemble layers of vector and raster geodata and render them in 2-D. You can
import, reorder, symbolize, hide, and delete data layers, identify coordinate
locations, list data attributes, and display selected ones as datatips (signposts
that identify attribute values, such as place names or route numbers). The
following exercise shows how the Map Viewer works and what it can do.
A Map Viewer Session
1 You start a Map Viewer session by typing
mapview
at the MATLAB prompt. The Map Viewer opens with a blank canvas (no
data is present). The viewer and its tools are shown below.
1-9
Getting Started
Print
figure
Select
area
Zoom
out
Insert
text
Zoom
in
Select
annotations
X and Y coordinate
readouts
Insert
line
Info
Insert
arrow
Pan
Fit to
window
Prior
view
Datatips
Map scale
Coordinate unit
drop-down
Currently active
layer drop-down
Most of the tool buttons can also be activated from the Tools menu.
2 For ease in importing Mapping Toolbox demo data, set your working
directory as follows:
cd(fullfile(matlabroot,'toolbox','map','mapdemos'))
However, you can also navigate to this directory with the Map Viewer
Import Data dialog if you prefer.
3 Select Import From File from the File menu and open the GeoTIFF file
boston.tif in the Map Viewer, as shown below.
1-10
Your First Maps
The file opens in the Map Viewer. The image is a visible red, green, and blue
composite from a georeferenced IKONOS-2 panchromatic/multispectral
product created by GeoEye. Copyright GeoEye, all rights reserved. For
further information about the image, refer to the text files boston.txt
and boston_metdata.txt.
4 To see the map scale, set the map distance units. Use the drop-down Map
units menu at the bottom center to select US Survey Feet.
5 Now set the scale to 1:25,000 by typing 1:25000 in the Scale box, which is
above the Map units drop-down. The viewer now looks like this.
1-11
Getting Started
Map scale
Note that the cursor is pointing at the front of the Massachusetts State
House (capitol building). The map coordinates for this location are shown
in the readout at the lower left as 774,114.36 feet easting (X), 2,955,685.56
feet northing (Y), in Massachusetts State Plane coordinates.
6 Next, import a vector data layer, the streets and highways in the central
Boston area from the line shapefile boston_roads.shp. However, as is
frequently the case when overlaying geodata, the coordinate system used by
boston_roads.shp (which has units of meters) does not completely agree
with the one for the satellite image, boston.tif (which uses units of feet).
If you were to ignore this, the two data sets would be out of registration by
quite a large distance.
Convert the units of boston_roads.shp to meters. First, read the file into
the workspace as a geographic data structure using shaperead, and then
1-12
Your First Maps
convert its X and Y coordinate fields from U.S. survey feet to meters using
the following code:
boston_roads = shaperead('boston_roads.shp');
surveyFeetPerMeter = unitsratio('survey feet','meter');
for k = 1:numel(boston_roads)
boston_roads(k).X = surveyFeetPerMeter * boston_roads(k).X;
boston_roads(k).Y = surveyFeetPerMeter * boston_roads(k).Y;
end
The unitsratio function computes conversion factors between a variety of
units of length.
7 Because you want to map data that is already in the workspace, this time
use Import From Workspace > Vector Data > Geographic Data
Structure from the File menu; specify boston_roads as the data to import
from the workspace, and click OK.
1-13
Getting Started
You could clear the workspace now if you wanted, because all the data that
mapview needs is now loaded into it.
8 After the Map Viewer finishes importing the roads layer, it selects a
random color and renders all the shapes with that color as solid lines. The
view looks like this.
1-14
Your First Maps
Active layer
Being random, the color you see for the road layer can differ. How you can
specify road colors is discussed below.
9 You can designate any layer to be the active layer (the one that you can
query); it does not need to be the topmost layer. By default, no layer is
active. Use the Active layer drop-down menu at the bottom left to select
boston_roads.
Changing the active layer has no visual effect. Doing so allows you to query
attributes of the layer you select.
10 One way to see the attributes for a vector layer is to use the Info tool, a
button near the right end of the toolbar. Select the Info tool and click
somewhere along the bridge across the Charles River near the lower left of
the map. This opens a text window displaying the attribute/values for the
selected object.
1-15
Getting Started
Info
The selected road is Massachusetts Avenue (Route 2A). As the above figure
shows, the boston_roads vectors have six attributes.
11 Get information about some other roads. Dismiss open Info windows by
clicking their close boxes.
12 Choose an attribute for the Datatip tool to inspect. From the Layers
menu, select boston_roads > Set Label Attribute. From the list in the
list box of the Attribute Names dialog, select CLASS and click OK to dismiss
it. The dialog looks like this.
1-16
Your First Maps
13 Select the Datatip tool. The cursor assumes a crosshairs (+) shape.
14 Use the Datatip tool to identify the administrative class of any road
displayed. When you click on a road segment, a data tip is left in that place
to indicate the CLASS attribute of the active layer, as illustrated below.
1-17
Getting Started
Data tip
15 You can change how the roads are rendered by identifying an attribute to
which to key line symbology. Color roads according to their CLASS attribute,
which takes on the values 1:6. Do this by creating a symbolspec in the
workspace. A symbolspec is a cell array that associates attribute names
and values to graphic properties for a specified geometric class ('Point',
'MultiPoint', 'Line', 'Polygon', or 'Patch'). To create a symbolspec for
line objects (in this case roads) that have a CLASS attribute, type
roadcolors = makesymbolspec('Line', ...
{'CLASS',1,'Color',[1 1 1]}, {'CLASS',2,'Color',[1 1 0]}, ...
{'CLASS',3,'Color',[0 1 0]}, {'CLASS',4,'Color',[0 1 1]}, ...
{'CLASS',5,'Color',[1 0 1]}, {'CLASS',6,'Color',[0 0 1]})
roadcolors =
ShapeType: 'Line'
Color: {6x3 cell}
1-18
Your First Maps
16 The Map Viewer recognizes and imports symbolspecs from the workspace.
To apply the one you just created, select boston_roads > Set Symbol
Spec from the Layers menu. From the Set Symbol Spec dialog, select the
roadcolors symbolspec you just created and click OK. After mapview has
read and applied the symbolspec, the map looks like this.
17 Remove the datatips before going on. To dismiss data tips, right-click each
of them and select Delete datatip or Delete all datatips from the pop-up
context menu that appears.
18 Add another layer, a set of points that identify 13 Boston landmarks. As
you did with the boston_roads layer, you import it from a shapefile. The
locations for these landmarks are also given in meters, so you must convert
their coordinates to units of survey feet before importing them into Map
Viewer, as before.
1-19
Getting Started
Read the shapefile and convert from meters to survey feet using this code:
boston_placenames = shaperead('boston_placenames.shp');
surveyFeetPerMeter = unitsratio('survey feet','meter');
for k = 1:numel(boston_placenames)
boston_placenames(k).X = ...
surveyFeetPerMeter * boston_placenames(k).X;
boston_placenames(k).Y = ...
surveyFeetPerMeter * boston_placenames(k).Y;
end
From the File menu choose Import From Workspace > Vector Data
> Geographic Data Structure; choose boston_placenames as the data
to import from the workspace by selecting it, and click OK:
The points of interest are symbolized as small x markers.
19 As the boston_placenames markers are difficult to see over the orthophoto,
hide the other map layers temporarily. To do this, go to the Layers menu,
select boston_roads, and then slide right and deselect Visible. Do the
same to hide the boston image layer.
You can now see the 13 markers showing points of interest.
20 To make the markers more visually prominent, create a symbolspec for
them to represent them as red filled circles. At the MATLAB command
line, type
places = makesymbolspec('Point',{'Default','Marker','o', ...
'MarkerEdgeColor','r','MarkerFaceColor','r'})
The Default keyword causes the specified symbol to be applied to all point
objects in a given layer unless specifically overridden by an attribute-coded
symbol in the same or a different symbolspec.
21 To activate this symbolspec, pull down the Layers menu, select
boston_placenames, slide right, and select Set Symbol Spec. In the
Layer Symbols dialog that appears, highlight places and click OK.
1-20
Your First Maps
The Map Viewer reads the workspace variable places; the cross marks
turn into red circles. Note that a layer need not be active in order for you
to apply a symbolspec to it.
22 Now restore the other layers visibility. In the Layers menu, select
boston_roads, and then slide right and select Visible. Do the same to
show the boston image layer. The boston_placenames marker layer,
because it was read in most recently, is on top.
23 Use the Active layer drop-down menu to make boston_placenames the
currently active layer, and then select the Datatip tool. Click any red
circle to see the name of the feature it marks. The map looks like this
(depending on which data tips you show).
24 Zoom in on Beacon Hill for a closer view of the Massachusetts State House
and Boston Common. Select the Zoom in tool, move the (magnifier) cursor
1-21
Getting Started
until the X readout is approximately 236,000 M and the Y readout is
roughly 900,900 M, then click once to enlarge the view. The scale changes
to about 1:10,000 and the map appears as below.
Zoom in
25 Right-click any of the data tips and select Delete all datatips from the
pop-up context menu. This clears the place names you added to the maps.
26 Select an area of interest to save as an image file. Click the Select
area tool, and then hold the mouse button down as you draw a selection
rectangle. If you do not like the selection, repeat the operation until you
are satisfied. If you know what ground coordinates you want, you can use
the coordinate readouts to make a precise selection. The selected area
appears as a red rectangle.
1-22
Your First Maps
27 In order to be able to save a file in the next step, change your working
directory to a writable directory, such as /work.
28 Save your selection as an image file. From the File menu, select Save As
Raster Map > Selected Area to open a Save As dialog, as shown below.
In the Export to File dialog, navigate to a directory where you want to
save the map image, and save the selected areas image as a .tif file,
calling it central_boston.tif (PNG and JPG formats are also available).
A worldfile, central_boston.tfw, is created there along with the TIF.
Whenever you save a raster map in this manner, two files are created:
An image file (file.tif, file.png, or file.jpg)
1-23
Getting Started
An accompanying worldfile that georeferences the image (file.tfw,
file.pgw, or file.jgw)
The following steps shows you how to read such files and display a
georeferenced image outside of mapview.
29 Read in the saved image and its colormap with the MATLAB
function imread, create a referencing matrix for it by reading in
central_boston.tfw with worldfileread, and display with mapshow:
[image cmap] = imread('central_boston.tif');
R = worldfileread('central_boston.tfw');
figure
mapshow(image, cmap, R);
See the documentation for mapshow for another example of displaying a
georeferenced image.
30 Experiment with other tools and menu items. For example, you can
annotate the map with lines, arrows, and text, fit the map to the window,
1-24
Your First Maps
draw a bounding box for any layer, and print the current view. You can
also spawn a new Map Viewer using New View from the File menu. A
new view can duplicate the current view, cover the active layers extent,
cover all layer extents, or include only the selected area, if any. When
you are through with a viewing session, close the Map Viewer using the
windows close box or select Close from the File menu.
1-25
Getting Started
Getting More Help
In this section...
Ways to Get Mapping Toolbox Help on page 1-26
Consulting Release Notes on page 1-26
Ways to Get Mapping Toolbox Help
The Mapping Toolbox documentation is available in electronic form as PDF
and HTML files through the helpdesk command. You might want to
print the reference chapters to browse through them. This is best
done from the PDF version, available at the MathWorks Web site,
http://www.mathworks.com/access/helpdesk/help/pdf_doc/map/map_ug.pdf.
You can find a classified list of functions in the Geospatial Data Import and
Access on page 11-2 (online only). Help is available for individual commands
and classes of Mapping Toolbox commands:
help map for computational functions
mapdemos for a list of Mapping Toolbox demos
maps lists all Mapping Toolbox map projections by class, name, and ID
string.
maplist returns a structure describing all Mapping Toolbox map
projections.
projlist to list map projections supported by projfwd and projinv
help functionname for help on a specific function, often including examples
helpwin functioname to see the output of help displayed in the Help
browser window instead of the Command Window
doc functionname to read a functions reference page in the Help browser,
including examples and illustrations
Consulting Release Notes
To learn how one version of Mapping Toolbox software differs from the next
and what important changes have been introduced in it, read the Mapping
1-26
Getting More Help
Toolbox Release Notes, which include information on enhancements, syntax
and GUI changes, known software and documentation problems, and
compatibility issues.
1-27
Getting Started
Mapping Toolbox Demos and Data
In this section...
Available Demos on page 1-28
Locating Geospatial Data on page 1-29
Available Demos
You can run demonstrations of Mapping Toolbox functions to further acquaint
you with their use. Most of the demos highlight and explain features added
in the current version. To see the full list of demos, click the Demos icon
in the Contents pane in the Help Navigator. Another way to obtain this
list is to type
mapdemos
at the MATLAB prompt. This will bring the Help browser to the fore.
When you view any of the following demos, you can then execute and view
its code by clicking links in the banner for that page that say Run in the
Command Window and Open <demo>.m in the Editor:
mapexkmlexport Exporting Vector Point Data to KML
mapexfindcity Interactive Global City Finder
mapexgeo Creating Maps Using geoshow (for latitude, longitude data)
mapexmap Creating Maps Using mapshow (for x, y data)
mapexrefmat Creating a Half-Resolution Georeferenced Image
mapexreg Georeferencing an Image to an Orthotile Base Layer
mapex3ddome Plotting a 3-D Dome as a Mesh Over a Globe
mapexunprojectdem Un-Projecting a Digital Elevation Model (DEM)
mapexgshhs Converting Coastline Data (GSHHS) to Shapefile Format
mapexwmsanimate Compositing and Animating Web Map Service
(WMS) Meteorological Layers
1-28
Mapping Toolbox Demos and Data
You can type
help mapdemos
to see this list of links as well as descriptions of the sample data provided
in Mapping Toolbox.
Locating Geospatial Data
Sample data sets are provided in the Mapping Toolbox mapdemos
directory. You can find them along with the demos described below in
toolbox\map\mapdemos. Most of the sample data sets have .txt files that
provide information or metadata about the their source and content.
For information on locating digital map data you can download over the
Internet, see the following documentation at the MathWorks Web site.
http://www.mathworks.com/support/tech-notes/2100/2101.html
1-29
1-30
Getting Started
2
Understanding Map Data
Maps and Map Data on page 2-2
Types of Map Data Handled by the Toolbox on page 2-4
Understanding Vector Geodata on page 2-13
Understanding Raster Geodata on page 2-33
Reading and Writing Geospatial Data on page 2-52
Understanding Map Data
Maps and Map Data
In this section...
What Is a Map? on page 2-2
What Is Geospatial Data? on page 2-2
What Is a Map?
Mapping Toolbox software manipulates electronic representations of
geographic data. It lets you import, create, use, and present geographic data
in a variety of forms and to a variety of ends. In the digital network era, it is
easy to think of geospatial data as maps and maps as data, but you should
take care to note the differences between these concepts.
The simplest (although perhaps not the most general) definition of a map is a
representation of geographic data. Most people today generally think of maps
as two-dimensional; to the ancient Egyptians, however, maps first took the
form of lists of place names in the order they would be encountered when
following a given road. Today such a list would be considered as map data
rather than as a map. When most people hear the word map they tend
to visualize two-dimensional renditions such as printed road, political, and
topographic maps, but even classroom globes and computer graphic flight
simulation scenes are maps under this definition.
In this toolbox, map data is any variable or set of variables representing a
set of geographic locations, properties of a region, or features on a planets
surface, regardless of how large or complex the data is, or how it is formatted.
Such data can be rendered as maps in a variety of ways using the functions
and user interfaces provided.
What Is Geospatial Data?
Geospatial data comes in many forms and formats, and its structure is more
complicated than tabular or even nongeographic geometric data. It is, in fact,
a subset of spatial data, which is simply data that indicates where things are
within a given coordinate system. Mileposts on a highway, an engineering
drawing of an automobile part, and a rendering of a building elevation
all have coordinate systems, and can be represented as spatial data when
2-2
Maps and Map Data
properly quantified (digitized). Such coordinate systems, however, are local
and not explicitly tied or oriented to the Earths surface; thus, most digital
representations of mileposts, machine parts, and buildings do not qualify as
geospatial data (also called geodata).
What sets geospatial data apart from other spatial data is that it is absolutely
or relatively positioned on a planet, or georeferenced. That is, it has a
terrestrial coordinate system that can be shared by other geospatial data.
There are many ways to define a terrestrial coordinate system and also to
transform it to any number of local coordinate systems, for example, to create
a map projection. However, most are based on a framework that represents a
planet as a sphere or spheroid that spins on a north-south axis, and which
is girded by an equator (an imaginary plane midway between the poles and
perpendicular to the rotational axis).
Geodata is coded for computer storage and applications in two principal ways:
vector and raster representations. It has been said that raster is faster but
vector is corrector. There is truth to this, but the situation is more complex.
The following discussions explore these two representations: how they differ,
what data structures support them, why you would choose one over the other,
and how they can work together in the toolbox. The conclude by summarizing
the functions available for importing and exporting geospatial data formats.
2-3
Understanding Map Data
Types of Map Data Handled by the Toolbox
In this section...
Vector Geodata on page 2-4
Raster Geodata on page 2-7
Combining Vector and Raster Geodata on page 2-10
Vector Geodata
Vector data (in the computer graphics sense rather than the physics
sense) can represent a map. Such vectors take the form of sequences of
latitude-longitude or projected coordinate pairs representing a point set, a
linear map feature, or an areal map feature. For example, points delineating
the boundary of the United States, the interstate highway system, the centers
of major U.S. cities, or even all three sets taken together, can be used to make
a map. In such representations, the geographic data is in vector format and
displays of it are referred to as vector maps. Such data consists of lists of
specific coordinate locations (which, if describing linear or areal features, are
normally points of inflection where line direction changes), along with some
indication of whether each is connected to the points adjacent to it in the list.
In the Mapping Toolbox environment, vector data consists of sequentially
ordered pairs of geographic (latitude, longitude) or projected (x,y) coordinate
pairs (also called tuples). Successive pairs are assumed to be connected
in sequence; breaks in connectivity must be delineated by the creation of
separate vector variables or by inserting separators (usually NaNs) into the
sets at each breakpoint. For vector map data, the connectivity (topological
structure) of the data is often only a concern during display, but it also affects
the computation of statistics such as length and area.
A Look at Vector Data
1 To inspect an example of vector map data, enter the following commands:
load coast
whos
Name
2-4
Size
Bytes
Class
Attributes
Types of Map Data Handled by the Toolbox
ans
lat
long
1x45
9589x1
9589x1
90
76712
76712
char
double
double
The variables lat and long are vectors in the coast MAT-file, which
together form a vector map of the coastlines of the world.
2 To view a map of this data, enter these commands:
axesm mercator
framem
plotm(lat,long)
Inspect the first 20 coordinates of the coastline vector data:
[lat(1:20) long(1:20)]
2-5
Understanding Map Data
ans =
-83.83 -180
-84.33 -178
-84.5 -174
-84.67 -170
-84.92 -166
-85.42 -163
-85.42 -158
-85.58 -152
-85.33 -146
-84.83 -147
-84.5 -151
-84 -153.5
-83.5 -153
-83 -154
-82.5 -154
-82 -154
-81.5 -154.5
-81.17 -153
-81 -150
-80.92 -146.5
Does this give you any clue as to which continents coastline these locations
represent?
3 To see the coastline these vector points represent, type this command to
display them in red:
plotm(lat(1:20), long(1:20),'r')
As you may have deduced by looking at the first column of the data, there
is only one continent that lies below -80 latitude, Antarctica.
The above example presents the map in a Mercator projection. A map
projection displays the surface of a sphere (or a spheroid) in a two-dimensional
plane. As the word plane indicates, points on the sphere are geometrically
projected to a plane surface. There are many possible ways to project a map,
all of which introduce various types of distortions.
For further information on how Mapping Toolbox software manages map
projections, see Chapter 8, Using Map Projections and Coordinate Systems.
2-6
Types of Map Data Handled by the Toolbox
For details on data structures that the toolbox uses to represent vector
geodata, see Mapping Toolbox Geographic Data Structures on page 2-16.
Raster Geodata
You can also map data represented as a matrix (a 2-D MATLAB array) in
which each row-and-column element corresponds to a rectangular patch of
a specific geographic area, with implied topological connectivity to adjacent
patches. This is commonly referred to as raster data. Raster is actually a
hardware term meaning a systematic scan of an image that encodes it into a
regular grid of pixel values arrayed in rows and columns.
When data in raster format represents the surface of a planet, it is called a
data grid, and the data is stored as an array or matrix. The toolbox leverages
the power of MATLAB matrix manipulation in handling this type of map data.
This documentation uses the terms raster data and data grid interchangeably
to talk about geodata stored in two-dimensional array form.
A raster can encode either an average value across a cell or a value sampled
(posted) at the center of that cell. While geolocated data grids explicitly
indicate which type of values are present (see Geolocated Data Grids on
page 2-44), external metadata/user knowledge is required to be able to specify
whether a regular data grid encodes averages or samples of values.
Digital Elevation Data
When raster geodata consists of surface elevations, the map can also be
referred to as a digital elevation model/matrix (DEM), and its display is a
topographical map. The DEM is one of the most common forms of digital
terrain model (DTM), which can also be represented as contour lines,
triangulated elevation points, quadtrees, octtrees, or otherwise.
The topo global terrain data is an example of a DEM. In this 180-by-360
matrix, each row represents one degree of latitude, and each column
represents one degree of longitude. Each element of this matrix is the average
elevation, in meters, for the one-degree-by-one-degree region of the Earth to
which its row and column correspond.
2-7
Understanding Map Data
Remotely Sensed Image Data
Raster geodata also encompasses georeferenced imagery. Like data grids,
images are organized into rows and columns. There are subtle distinctions,
however, which are important in certain contexts. One distinction is that an
image may contain RGB or multispectral channels in a single array, so that
it has a third (color or spectral) dimension. In this case a 3-D array is used
rather than a 2-D (matrix) array. Another distinction is that while data grids
are stored as class double in the toolbox, images may use a range of MATLAB
storage classes, with the most common being uint8, uint16, double, and
logical. Finally, for grayscale and RGB images of class double, the values of
individual array elements are constrained to the interval [0 1].
In terms of georeferencingconverting between column/row subscripts
and 2-D map or geographic coordinatesimages and data grids behave the
same way (which is why both are considered to be a form of raster geodata).
However, when performing operations that process the values raster elements
themselves, including most display functions, it is important to be aware of
whether you are working with an image or a data grid, and for images, how
spectral data is encoded.
For further details concerning the structure of raster map data, see
Understanding Raster Geodata on page 2-33.
A Look at Raster Data
1 Load the topo data grid.
load topo topo
2 topo contains raster elevation data. Create a referencing matrix to
georeference topo.
topoR = makerefmat('RasterSize', size(topo), ...
'Latlim', [-90 90], 'Lonlim', [-180 180]);
3 Create an equal-area map projection to view the topographic data:
axesm sinusoid
2-8
Types of Map Data Handled by the Toolbox
A figure window is created with map axes set to display a sinusoidal
projection.
4 Generate a shaded relief map. You can do this in several ways. First use
geoshow and apply a topographic colormap using demcmap:
geoshow(topo,topoR,'DisplayType','texturemap')
demcmap(topo)
The geoshow function displays geodata in geographic (unprojected)
coordinates. The geoshow output is shown below:
5 Now create a new figure using a Hammer projection (which, like the
sinusoidal, is also equal-area), and display topo using meshlsrm, which
enables control of lighting effects:
figure; axesm hammer
meshlsrm(topo,topoR)
A colored relief map of the topo data set, illuminated from the east, is
rendered in the second figure window.
2-9
Understanding Map Data
For additional details on controlling the illumination of maps, see Shading
and Lighting Terrain Maps on page 5-22.
Note that the content, symbolization, and the projection of the map are
completely independent. The structure and content of the topo variable are
the same no matter how you display it, although how it is projected and
symbolized can affect its interpretation. The following example illustrates
this.
Combining Vector and Raster Geodata
Vector map variables and data grid variables are often used or displayed
together. For example, continental coastlines in vector form might be
displayed with a grid of temperature data to make the latter more useful.
When several map variables are used together, regardless of type, they can
be referred to as a single map. To do this, of course, the different data sets
must use the same coordinate system (i.e., geographic coordinates on the
same ellipsoid or an identical map projection). See Chapter 3, Understanding
Geospatial Geometry for an introduction to these concepts.
Viewing Raster and Vector Data on the Same Map
Using the coast and topo data from the previous examples, you can combine
them in a single map and see how well the two types of data work together:
1 Clear the current map:
clma
2-10
Types of Map Data Handled by the Toolbox
2 Reload the coastline data:
load coast
3 If the topo data is not already in the workspace, load it as well:
load topo
4 Set up a Robinson projection:
axesm robinson
5 Plot the raster topographic data with an appropriate colormap:
geoshow(topo,topolegend,'DisplayType','texturemap')
demcmap(topo)
6 Plot the coastline data in white on top of the terrain map:
geoshow(lat,long,'Color','r')
Note that you can use geoshow to display both raster and vector data. Here
is the resulting map.
For additional details on how Mapping Toolbox functions handles raster
geodata, see Understanding Raster Geodata on page 2-33.
The remainder of this chapter focuses on the fundamental principles of
geographic measurement and data manipulation that are a prerequisite for
creating map displays. Reading and Writing Geospatial Data on page 2-52
2-11
Understanding Map Data
summarizes input functions for importing many formats of geospatial data
into the toolbox. Chapter 3, Understanding Geospatial Geometry introduces
geodetic concepts that underlie all geospatial data and its handling.
2-12
Understanding Vector Geodata
Understanding Vector Geodata
In this section...
Points, Lines, Polygons on page 2-13
Segments Versus Polygons on page 2-15
Mapping Toolbox Geographic Data Structures on page 2-16
Selecting Data to Read with the shaperead Function on page 2-27
Points, Lines, Polygons
Vector geospatial data is used to represent linear features such as rivers,
coastlines, boundaries, and highways. Vector data can also represent areal
features such as water bodies, political units, and enumeration districts. This
section familiarizes you with how vector data structures digitally encode
geographic entities and how to use this form of data.
In the context of geodata, vector data means geometric descriptions of
geographic objects rather than its more general mathematical definition,
a quantity specified by a magnitude and a direction. In fact, some vector
geodata is specified as points having neither magnitude nor direction. Other
geodatasuch as postcodes, highway mileposts, or census statisticsonly
implies an underlying geometry, which vector 2-D coordinate data is required
to map or spatially analyze.
In the MATLAB workspace, vector data is expressed as pairs of variables that
represent the geographic or plane coordinates for a set of points of interest.
For example, the following two variables can be mapped as a vector:
lat = [45.6 -23.47 78];
long = [13 -97.45 165];
Note that either row or column vectors can be used, but both variables should
have the same shape. For example, lat and long could be defined as columns:
lat = [45.6 -23.47 78]';
long = [13 -97.45 165]';
2-13
Understanding Map Data
These values could mean anything. They could represent three locations over
which geosynchronous satellites are stationed, and can be communicated by
plotting a symbol for each point on a map of the Earth. Alternatively, they
might represent a starting point, a midcourse marker, and a finish point
of a sailboat race, in which case they can be rendered by plotting two line
segments. Or perhaps the values represent the vertices of a triangle bounding
a region of interest, and thus constitute a simple polygon.
Note When polygons become graphic objects, they are called patches. In this
documentation, the words patch and polygon are often used interchangeably.
Mapping Toolbox functions provide for each of these interpretations. For
many purposes, the distinction is irrelevant; for others, the choice of a
function implies one interpretation over the others. For example, the function
plotm displays the data as a line, while fillm displays it as a filled polygon.
While you can draw an unfilled polygon with fillm that looks like the output
from plotm, the resulting object has a different graphic data type (patch
versus line), hence different properties you can set.
A line must contain at least two coordinate elements for each coordinate
dimension, and a polygon at least three (note that it is not necessary to
duplicate the first point as the last point to define or render a polygon).
The toolbox places no limit (beyond available memory) on how large or how
complex the shape of a line and polygon can be, other than the restriction
that it should not cross itself.
Objects in the real world that vector geodata represents can have many parts,
for example, the islands that make up the state of Hawaii. When encoding
as vector variables the shapes of such compound entities, you must separate
successive entities. To indicate that such a discontinuity exists, the toolbox
uses the convention of placing NaNs in identical positions in both vector
variables. For example, if a second segment is to be added to the preceding
map, the two objects can reside in the same pair of variables:
lat = [45.6 -23.47 78 NaN 43.9 -67.14 90 -89];
lon = [13 -97.45 165 NaN 0 -114.2 -18 0];
2-14
Understanding Vector Geodata
Notice that the NaNs must appear in the same locations in both variables.
Here is a segment of three points separated from a segment of four points. The
NaNs perform two functions: they provide a means of identifying breakpoints
in the data, and they serve as pen-up commands when plotting vector maps.
The NaNs are used to separate both distinct (but possibly connecting) lines
and disconnected patch faces.
Note This convention departs from regular MATLAB graphics, in which
NaN-separated polygons cannot be interpreted or displayed as separate
patches.
Segments Versus Polygons
Geographic objects represented by vector data might or might not be
formatted as polygons. Imagine two variables, latcoast and loncoast, that
correspond to a sequence of points that caricature the coast of the island
of Great Britain. If this data returns to its starting point, then a polygon
describing Great Britain exists. This data might be plotted as a patch or as a
line, and it might be logically employed in calculations as either.
Now suppose you want to represent the Anglo-Scottish border, proceeding
from the west coast at Solway Firth to the east coast at Berwick-upon-Tweed.
This data can only be properly defined as a line, defined by two or more points,
which you can represent with two more variables, latborder and lonborder.
When plotted together, the two pairs of variables can form a map. The patch
of Great Britain plus the line showing the Scottish border might look like two
patches or regions, but there is no object that represents England and no
object that represents Scotland, either in the workspace or on the map axes.
In order to represent both regions properly, the Great Britain polygon needs to
be split at the two points where the border meets it, and a copy of latborder
and lonborder concatenated to both lines (placing one in reverse order). The
resulting two polygons can be represented separately (e.g., in four variables
named latengland, lonengland, latscotland, and lonscotland) or in two
variables that define two polygons each, delineated by NaNs (e.g., latuk,
lonuk).
2-15
Understanding Map Data
Border line
Polygon of Great Britain
Polygon and line together
(still one polygon)
The distinction between line and polygon data might not appear to be
important, but it can make a difference when you are performing geographic
analysis and thematic mapping. For example, polygon data can be treated as
line data and displayed with functions such as linem, but line data cannot
be handled as polygons unless it is restructured to make all objects close on
themselves, as described in Matching Line Segments on page 7-4.
Mapping Toolbox Geographic Data Structures
In examples provided in prior chapters, geodata was in the form of individual
variables. Mapping Toolbox software also provides an easy means of
displaying, extracting, and manipulating collections vector map features
that have been organized in a family of specially organized geographic data
structures.
2-16
Understanding Vector Geodata
Note The data structures discussed in this section are different from the map
projection structure (also called an mstruct), which defines a map projection
and related display properties for map axes. See the defaultm function
reference page for information about mstructs.
The following subsections describe what the geographic data structures
contain and how to create and display them. Version 1 of the toolbox used a
different kind of geographic data structure (called a display structure), which
had a more rigid definition.
Note Version 1 display structures are being phased out of the toolbox
and are currently generated only by a few functions. You can use the
updategeostruct to convert a display structure containing vector features
to a geographic data structure. You must do this in order to export data
imported from VMAP level 0 or DCW data sets with shapewrite, for example.
For more information, see the displaym reference page, which describes the
format and contents of display structures.
Representing Geographic Features
Certain Mapping Toolbox functions read, create, or manipulate vector
geodata organized within a geographic data structure. This is a MATLAB
structure array that has one element per geographic feature. Each feature is
represented by coordinates and any kind and number of attributes. When it
holds geographic coordinates (latitude and longitude), it is called a geostruct;
when it contains plane (projected x and y) map coordinates, it is called a
mapstruct.
Geostructs and mapstructs most frequently originate when vector geodata
is imported from a shapefile. They hold only vector features and cannot be
used to hold raster data, whether images, regular data grids, or geolocated
data grids. The shaperead function returns either a geostruct or a mapstruct
that encapsulates some or all of the data stored in a shapefile data set (which
stores attributes and coordinates in separate files). The gshhs function also
returns a geostruct.
2-17
Understanding Map Data
By default, shaperead returns a mapstruct containing X and Y fields. This
is appropriate if the data set coordinates are already projected (are in map
space). Otherwise, when the coordinate data is unprojected (are in geographic
space ), use the parameter-value pair 'UseGeoCoords',true to make
shaperead return a geostruct having Lon and Lat fields instead. If you do
not know whether coordinates in the shapefile are projected or unprojected,
ask your data provider.
To determine what kinds of data a shapefile data set contains, query the
data set using the shapeinfo function. shapeinfo returns a 1-by-1 structure
containing high-level descriptions; it cannot be used as a geostruct or
mapstruct.
Geographic data structures conform to a few simple rules, making them easy
to construct programmatically:
Each array element represents an entity of the same geometric class (Point,
MultiPoint, Line, or Polygon).
Geostructs: For geographic coordinates, the fields Geometry, Lat, and Lon
must be present.
Mapstructs: For plane coordinates, the fields Geometry, Y, and X must
be present.
Except for Point geometry, a field called BoundingBox that contains
[minX minY; maxX maxY] is provided.
If present, additional fields (for attributes) must contain either strings or
scalar numbers.
Coordinate data is stored in fields called X or Lon and Y or Lat, depending
on what type of coordinates were read in or placed there. The mandatory
coordinate field names tell map display and data export functions that accept
geographic data structures whether a map projection has already been
applied to coordinates, which can prevent them from generating erroneous
data and graphics. Be aware that a mapstruct does not itself identify the
map projection or projection parameters to which the X and Y coordinates are
referenced. This is also generally true for geodata stored in shapefiles; see the
shapeinfo reference page for more information.
2-18
Understanding Vector Geodata
Any number of attribute fields can be included in a geostruct or mapstruct,
and can contain either a double or a string data type. This type must be
consistent for a given attribute across all elements of the structure array. The
fields in a geostruct representing imported data can vary according to the type
of geometry and the names of attributes that have been read. If a shapefile
attribute name cannot be directly used as a field name, shaperead assigns
the field an appropriately mangled name, usually by substituting underscores
for spaces. shaperead can filter out unwanted attributes; see Selecting Data
to Read with the shaperead Function on page 2-27 for information on how
to set up such filters.
Here is an example of an unfiltered mapstruct returned by shaperead:
S = shaperead('concord_roads.shp')
S =
609x1 struct array with fields:
Geometry
BoundingBox
X
Y
STREETNAME
RT_NUMBER
CLASS
ADMIN_TYPE
LENGTH
This indicates that the shapefile contains 609 features. In addition to the
Geometry, BoundingBox, and coordinate fields (X and Y), there are five
attribute fields: STREETNAME, RT_NUMBER, CLASS, ADMIN_TYPE, and LENGTH.
Looking at the 10th element,
S(10)
ans =
Geometry:
BoundingBox:
X:
Y:
STREETNAME:
RT_NUMBER:
'Line'
[2x2 double]
[1x9 double]
[1x9 double]
'WRIGHT FARM'
''
2-19
Understanding Map Data
CLASS: 5
ADMIN_TYPE: 0
LENGTH: 79.0347
you can see that this mapstruct contains line features, and that the tenth
line has nine vertices. The first two attributes are string-valued (the second
happens to be empty), and the final three attributes are numeric. Across
the elements of S, X and Y can have various lengths, but STREETNAME and
RT_NUMBER must always contain strings, and CLASS, ADMIN_TYPE, and LENGTH
must always contain scalar doubles.
Note In mapstructs and geostructs having Line or Polygon geometries,
individual features can have multiple partsseparated, disconnected line
segments and polygon rings. The parts can include inner rings that run
counterclockwise and outline voids. Each disconnected part is separated from
the next by a NaN within the X and Y (or Lat and Lon) vectors. You can use
the isShapeMultipart function to determine if a feature has NaN-separated
parts.
Each NaN-separated multipart line, polygon, or multipoint entity constitutes
a single feature and thus has one string or scalar double value per attribute
field. It is not possible to assign distinct attributes to the different parts of
such a feature; any string or numeric attribute imported with (or subsequently
added to) the geostruct or mapstruct applies to all the features parts.
How to Construct Geostructs and Mapstructs
Functions such as shaperead or gshhs return geostructs when importing
vector geodata. However, you might want to create geostructs or mapstructs
yourself in some circumstances. For example, you might import vector
geodata that is not stored in a shapefile (for example, from a MAT-file, from
an Microsoft Excel spreadsheet, or by reading in a delimited text file). You
also might compute vector geodata and attributes by calling various MATLAB
or Mapping Toolbox functions. In both cases, the coordinates and other data
are typically vectors or matrices in the workspace. Packaging variables into a
geostruct or mapstruct can make mapping and exporting them easier, because
geographic data structures provide several advantages over coordinate arrays:
2-20
Understanding Vector Geodata
All associated geodata variables are packaged in one container, a structure
array.
The structure is self-documenting through its field names.
You can vary map symbology for points, lines, and polygons according to
their attribute values by constructing a symbolspec for displaying the
geostruct or mapstruct.
A one-to-one correspondence exists between structure elements and
geographic features, which extends to the children of hggroups constructed
by mapshow and geoshow.
Achieving these benefits is not difficult. Use the following example as a
guide to packaging vector geodata you import or create into geographic data
structures.
Example Making Point and Line Geostructs. The following example
first creates a point geostruct containing three cities on different continents
and plots it with geoshow. Then it creates a line geostruct containing data
for great circle navigational tracks connecting these cities. Finally, it plots
these lines using a symbolspec.
1 Begin with a small set of point data, approximate latitudes and longitudes
for three cities on three continents:
latparis = 48.87084; lonparis =
2.41306;
latsant = -33.36907; lonsant = -70.82851;
latnyc
= 40.69746; lonnyc
= -73.93008;
% Paris coords
% Santiago
% New York City
2 Build a point geostruct; it needs to have the following required fields:
Geometry (in this case 'Point')
Lat (for points, this is a scalar double)
Lon (for points, this is a scalar double)
% The first field by convention is Geometry (dimensionality).
% As Geometry is the same for all elements, assign it with deal:
[Cities(1:3).Geometry] = deal('Point');
% Add the latitudes and longitudes to the geostruct:
Cities(1).Lat = latparis; Cities(1).Lon = lonparis;
2-21
Understanding Map Data
Cities(2).Lat = latsant;
Cities(3).Lat = latnyc;
Cities(2).Lon = lonsant;
Cities(3).Lon = lonnyc;
% Add city names as City fields. You can name optional fields
% anything you like other than Geometry, Lat, Lon, X, or Y.
Cities(1).Name = 'Paris';
Cities(2).Name = 'Santiago';
Cities(3).Name = 'New York';
% Inspect your completed geostruct and its first member
Cities
Cities =
1x3 struct array with fields:
Geometry
Lat
Lon
Name
Cities(1)
ans =
Geometry:
Lat:
Lon:
Name:
'Point'
48.8708
2.4131
'Paris'
3 Display the geostruct on a Mercator projection of the Earths land masses
stored in the landareas.shp demo shapefile , setting map limits to exclude
polar regions:
axesm('mercator','grid','on','MapLatLimit',[-75 75]); tightmap;
% Map the geostruct with the continent outlines
geoshow('landareas.shp')
% Map the City locations with filled circular markers
geoshow(Cities,'Marker','o',...
'MarkerFaceColor','c','MarkerEdgeColor','k');
% Display the city names using data in the geostruct field Name.
% Note that you must treat the Name field as a cell array.
2-22
Understanding Vector Geodata
textm([Cities(:).Lat],[Cities(:).Lon],...
{Cities(:).Name},'FontWeight','bold');
4 Next, build a Line geostruct to package great circle navigational tracks
between the three cities:
% Call the new geostruct Tracks and give it a line geometry:
[Tracks(1:3).Geometry] = deal('Line');
% Create a text field identifying kind of track each entry is.
% Here they all will be great circles, identified as 'gc'
% (string signifying great circle arc to certain functions)
trackType = 'gc';
[Tracks.Type] = deal(trackType);
% Give each track an identifying name
Tracks(1).Name = 'Paris-Santiago';
[Tracks(1).Lat Tracks(1).Lon] = ...
track2(trackType,latparis,lonparis,latsant,lonsant);
Tracks(2).Name = 'Santiago-New York';
2-23
Understanding Map Data
[Tracks(2).Lat Tracks(2).Lon] = ...
track2(trackType,latsant,lonsant,latnyc,lonnyc);
Tracks(3).Name = 'New York-Paris';
[Tracks(3).Lat Tracks(3).Lon] = ...
track2(trackType,latnyc,lonnyc,latparis,lonparis);
5 Compute lengths of the great circle tracks:
% The distance function computes distance and azimuth between
% given points, in degrees. Store both in the geostruct.
for j = 1:numel(Tracks)
[dist az] = ...
distance(trackType,Tracks(j).Lat(1),...
Tracks(j).Lon(1),...
Tracks(j).Lat(end),...
Tracks(j).Lon(end));
[Tracks(j).Length] = dist;
[Tracks(j).Azimuth] = az;
end
% Inspect the first member of the completed geostruct
Tracks(1)
ans =
Geometry:
Type:
Name:
Lat:
Lon:
Length:
Azimuth:
'Line'
'gc'
'Paris-Santiago'
[100x1 double]
[100x1 double]
104.8274
235.8143
6 Map the three tracks in the line geostruct:
% On cylindrical projections like Mercator, great circle tracks
% are curved except those that follow the Equator or a meridian.
%
%
%
%
2-24
Graphically differentiate the tracks by creating a symbolspec;
key line color to track length, using the 'summer' colormap.
Symbolspecs make it easy to vary color and linetype by
attribute values. You can also specify default symbologies.
Understanding Vector Geodata
colorRange = makesymbolspec('Line',...
{'Length',[min([Tracks.Length]) ...
max([Tracks.Length])],...
'Color',winter(3)});
geoshow(Tracks,'SymbolSpec',colorRange);
You can save the geostructs you just created as shapefiles by calling
shapewrite with a filename of your choice, for example:
shapewrite(Cities,'citylocs');
shapewrite(Tracks,'citytracks');
2-25
Understanding Map Data
Making Polygon Geostructs. Creating a geostruct or mapstruct for
polygon data is similar to building one for point or line data. However, if your
polygons include multiple, NaN-separated parts, recall that they can have
only one value per attribute, not one value per part. Each attribute you place
in a structure element for such a polygon pertains to all its parts. This means
that if you define a group of islands, for example with a single NaN-separated
list for each coordinate, all attributes for that element describe the islands
as a group, not particular islands. If you want to associate attributes with
a particular island, you must provide a distinct structure element for that
island.
Be aware that the ordering of polygon vertices matters. When you map
polygon data, the direction in which polygons are traversed has significance
for how they are rendered by functions such as geoshow, mapshow, and
mapview. Proper directionality is particularly important if polygons contain
holes. The Mapping Toolbox convention encodes the coordinates of outer
rings (e.g., continent and island outlines) in clockwise order; counterclockwise
ordering is used for inner rings (e.g., lakes and inland seas). Within the
coordinate array, each ring is separated from the one preceding it by a NaN.
When plotted by mapshow or geoshow, clockwise rings are filled.
Counterclockwise rings are unfilled; any underlying symbology shows through
such holes. To ensure that outer and inner rings are correctly coded according
to the above convention, you can invoke the following functions:
ispolycw True if vertices of polygonal contour are clockwise ordered
poly2cw Convert polygonal contour to clockwise ordering
poly2ccw Convert polygonal contour to counterclockwise ordering
poly2fv Convert polygonal region to face-vertex form for use with patch
in order to properly render polygons containing holes
Three of these functions check or change the ordering of vertices that define
a polygon, and the fourth one converts polygons with holes to a completely
different representation.
For more information about working with polygon geostructs, see the
Mapping Toolbox Converting Coastline Data (GSHHS) to Shapefile Format
demo mapexgshhs.
2-26
Understanding Vector Geodata
Mapping Toolbox Version 1 Display Structures
Prior to Version 2, when geostructs and mapstructs were introduced, a
different data structure was employed when importing geodata from certain
external formats to encapsulate it for map display functions. These display
structures accommodated both raster and vector map data and other kinds
of objects, but lacked the generality of current geostructs and mapstructs
for representing vector features and are being phased out of the toolbox.
However, you can convert display structures that contain vector geodata to
geostruct form using updategeostruct. For more information about Version
1 display structures and their usage, see Version 1 Display Structures on
page 12-142 in the reference page for displaym. Additional information is
located in reference pages for updategeostruct, extractm, and mlayers.
Selecting Data to Read with the shaperead Function
The shaperead function provides you with a powerful method, called a
selector, to select only the data fields and items you want to import from
shapefiles.
A selector is a cell array with two or more elements. The first element is a
handle to a predicate function (a function with a single output argument of
type logical). Each remaining element is a string indicating the name of
an attribute.
For a given feature, shaperead supplies the values of the attributes listed to
the predicate function to help determine whether to include the feature in its
output. The feature is excluded if the predicate returns false. The converse
is not necessarily true: a feature for which the predicate returns true may be
excluded for other reasons when the selector is used in combination with the
bounding box or record number options.
The following examples are arranged in order of increasing sophistication.
Although they use MATLAB function handles, anonymous functions, and
nested functions, you need not be familiar with these features in order to
master the use of selectors for shaperead.
2-27
Understanding Map Data
Example 1: Predicate Function in Separate File
1 Define the predicate function in a separate file. (Prior to Release 14, this
was the only option available.) Create a file named roadfilter.m, with
the following contents:
function result = roadfilter(roadclass,roadlength)
mininumClass = 4;
minimumLength = 200;
result = (roadclass >= mininumClass) && ...
(roadlength >= minimumLength);
end
2 You can then call shaperead like this:
roadselector = {@roadfilter, 'CLASS', 'LENGTH'}
roadselector =
@roadfilter
'CLASS'
'LENGTH'
s = shaperead('concord_roads', 'Selector', roadselector)
s =
115x1 struct array with fields:
Geometry
BoundingBox
X
Y
STREETNAME
RT_NUMBER
CLASS
ADMIN_TYPE
LENGTH
or, in a slightly more compact fashion, like this:
s = shaperead('concord_roads',...
'Selector', {@roadfilter, 'CLASS', 'LENGTH'})
s =
115x1 struct array with fields:
2-28
Understanding Vector Geodata
Geometry
BoundingBox
X
Y
STREETNAME
RT_NUMBER
CLASS
ADMIN_TYPE
LENGTH
Prior to Version 7 of the Mapping Toolbox software, putting the selector in
a file or subfunction of its own was the only way to work with a selector.
Note that if the call to shaperead took place within a function, then
roadfilter could be defined in a subfunction thereof rather than in an
M-file of its own.
Example 2: Predicate as Function Handle
As a simple variation on the previous example, you could assign a function
handle, roadfilterfcn, and use it in the selector:
roadfilterfcn = @roadfilter
s = shaperead('concord_roads',...
'Selector', {roadfilterfcn, 'CLASS', 'LENGTH'})
roadfilterfcn =
@roadfilter
s =
115x1 struct array with fields:
Geometry
BoundingBox
X
Y
STREETNAME
RT_NUMBER
CLASS
ADMIN_TYPE
LENGTH
2-29
Understanding Map Data
Example 3: Predicate as Anonymous Function
Having to define predicate functions in M-files of their own, or even as
subfunctions, may sometimes be awkward. Anonymous functions allow the
predicate function to be defined right where it is needed. For example:
roadfilterfcn = ...
@(roadclass, roadlength) (roadclass >= 4) && ...
(roadlength >= 200)
roadfilterfcn =
@(roadclass, roadlength) (roadclass >= 4) ...
&& (roadlength >= 200)
s = shaperead('concord_roads','Selector', ...
{roadfilterfcn, 'CLASS', 'LENGTH'})
s =
115x1 struct array with fields:
Geometry
BoundingBox
X
Y
STREETNAME
RT_NUMBER
CLASS
ADMIN_TYPE
LENGTH
Example 4: Predicate (Anonymous Function) Defined Within
Cell Array
There is actually no need to introduce a function handle variable when
defining the predicate as an anonymous function. Instead, you can place the
whole expression within the selector cell array itself, resulting in somewhat
more compact code. This pattern is used in many examples throughout
Mapping Toolbox documentation and M-file help.
s = shaperead('concord_roads', 'Selector', ...
{@(roadclass, roadlength)...
(roadclass >= 4) && (roadlength >= 200),...
2-30
Understanding Vector Geodata
'CLASS', 'LENGTH'})
s =
115x1 struct array with fields:
Geometry
BoundingBox
X
Y
STREETNAME
RT_NUMBER
CLASS
ADMIN_TYPE
LENGTH
Example 5: Parameterizing the Selector; Predicate as Nested
Function
In the previous patterns, the predicate involves two hard-coded parameters
(called minimumClass and minimumLength in roadfilter.m), as well as
the roadclass and roadlength input variables. If you use any of these
patterns in a program, you need to decide on minimum cut-off values for
roadclass and roadlength at the time you write the program. But suppose
that you wanted to wait and decide on parameters like minimumClass and
minimumLength at run time?
Fortunately, nested functions provide the additional power that you need
to do this; they allow you utilize workspace variables in as parameters,
rather than requiring that the parameters be hard-coded as constants within
the predicate function. In the following example, the workspace variables
minimumClass and minimumLength could have been assigned through a
variety of computations whose results were unknown until run-time, yet their
values can be made available within the predicate as long as it is defined
as a nested function. In this example the nested function is wrapped in an
M-file called constructroadselector.m, which returns a complete selector:
a handle to the predicate (named nestedroadfilter) and the two attibute
names:
function roadselector = ...
constructroadselector(minimumClass, minimumLength)
roadselector = {@nestedroadfilter, 'CLASS', 'LENGTH'};
2-31
Understanding Map Data
function result = nestedroadfilter(roadclass, roadlength)
result = (roadclass >= minimumClass) && ...
(roadlength >= minimumLength);
end
end
The following four lines show how to use constructroadselector:
minimumClass = 4;
minimumLength = 200;
% Could be run-time dependent
% Could be run-time dependent
roadselector = constructroadselector(...
minimumClass, minimumLength);
s = shaperead('concord_roads', 'Selector', roadselector)
s =
115x1 struct array with fields:
Geometry
BoundingBox
X
Y
STREETNAME
RT_NUMBER
CLASS
ADMIN_TYPE
LENGTH
2-32
Understanding Raster Geodata
Understanding Raster Geodata
In this section...
Georeferencing Raster Data on page 2-33
Regular Data Grids on page 2-35
Geolocated Data Grids on page 2-44
Georeferencing Raster Data
Raster geodata consists of georeferenced data grids and images that in the
MATLAB workspace are stored as matrices. While raster geodata looks like
any other matrix of real numbers, what sets it apart is that it is georeferenced,
either to the globe or to a specified map projection, so that each pixel of data
occupies a known patch of territory on the planet.
Whether a raster geodata set covers the entire planet or not, its placement
and resolution must be specified. Raster geodata is georeferenced in the
toolbox through a companion data structure called a referencing matrix. This
3-by-2 matrix of doubles describes the scaling, orientation, and placement
of the data grid on the globe. For a given referencing matrix, R, one of
the following relations holds between rows and columns and coordinates
(depending on whether the grid is based on map coordinates or geographic
coordinates, respectively):
[x y] = [row col 1] * R, or
[long lat] = [row col 1] * R
For additional details about and examples of using referencing matrices, see
the reference page for makerefmat.
Referencing Vectors
In many instances (when the data grid or image is based on latitude and
longitude and is aligned with the geographic graticule), a referencing matrix
has more degrees of freedom than the data requires. In such cases, you can
use a more compact representation, a three-element referencing vector. A
referencing vector defines the pixel size and northwest origin for a regular,
rectangular data grid:
2-33
Understanding Map Data
refvec = [cells-per-degree north-lat west-lon]
In MAT-files, this variable is often called refvec or maplegend. The first
element, cells-per-degree, describes the angular extent of each grid cell (e.g., if
each cell covers five degrees of latitude and longitude, cells-per-degree would
be specified as 0.2). Note that if the latitude extent of cells differs from
their longitude extent you cannot use a referencing vector, and instead must
specify a referencing matrix. The second element, north-lat, specifies the
northern limit of the data grid (as a latitude), and the third element, west-lon,
specifies the western extent of the data grid (as a longitude). In other words,
north-lat, west-lon is the northwest corner of the data grid. Note, however,
that cell (1,1) is always in the southwest corner of the grid. This need not be
the case for grids or images described by referencing matrices, as opposed
to referencing vectors.
Note Versions of Mapping Toolbox software prior to 2.0 did not use
referencing matrices, and called referencing vectors map legend vectors or
sometimes just map legends. The current version of the toolbox uses the term
legend only to refer to keys to symbolism.
An example of such a grid is the geoid data set (a MAT-file), which represents
the shape of the geoid. In the geoid matrix, each cell represents one degree,
the entire northern edge occupies the north pole, the southern edge occupies
the south pole, and the western edge runs down the prime meridian. Thus,
the referencing vector for geoid is
geoidrefvec = [1 90 0]
This structure is stored in the geoid MAT-file (note that it is duplicated by
the geoidlegend referencing vector for backward compatibility). Interpret
this referencing vector as follows:
Each data grid entry represents one degree of latitude and one degree
of longitude.
The northern edge of the map is at 90N (the North Pole).
The western edge of the map is at 0 (the prime meridian).
2-34
Understanding Raster Geodata
All regular data grids require a referencing matrix or vector, even if they
cover the entire planet. Geolocated data grids do not, as they explicitly
identify the geographic coordinates of all rows and columns. For details on
geolocated grids, see Geolocated Data Grids on page 2-44. For additional
information on referencing matrices and vectors, see the reference pages
for makerefmat, limitm, and sizem.
Regular Data Grids
Regular data grids are rectangular, non-sparse, matrices of class double.
Constructing a Global Data Grid
Imagine an extremely coarse map of the world in which each cell represents
60. Such a map matrix would be 3-by-6.
1 First create data for this, starting with the data grid:
miniZ = [1 2 3 4 5 6; 7 8 9 10 11 12; 13 14 15 16 17 18];
2 Now make a referencing matrix:
miniR = makerefmat('RasterSize', size(miniZ), ...
'Latlim', [-90 90], 'Lonlim', [-180 180])
miniR =
0
60
-210
60
0
-120
3 Set up an equidistant cylindrical map projection:
axesm('MapProjection', 'eqdcylin')
setm(gca,'GLineStyle','-', 'Grid','on','Frame','on')
4 Draw a graticule with parallel and meridian labels at 60 intervals:
setm(gca, 'MlabelLocation', 60, 'PlabelLocation',[-30 30],...
'MLabelParallel','north', 'MeridianLabel','on',...
'ParallelLabel','on','MlineLocation',60,...
'PlineLocation',[-30 30])
2-35
Understanding Map Data
5 Map the data using meshm and display with a color ramp and legend:
meshm(miniZ, miniR); colormap('autumn'); colorbar
Note that the first row of the matrix is displayed as the bottom of the map,
while the last row is displayed as the top.
Computing Map Limits from Referencing Vectors
Given a regular data grid and its referencing vector, the full extent of the grid
can be computed using the limitm function. To understand how this works for
a data grid that does not encompass the entire world, do the following exercise:
1 Load the Korea 5-arc-minute elevation grid and inspect the referencing
vector, refvec:
load korea
refvec
refvec =
2-36
Understanding Raster Geodata
12
45
115
The refvec referencing vector indicates that there are 12 cells per angular
degree. This horizontal resolution is 5 times finer than that of the topo
data grid, which is one cell per degree.
2 Use limitm to determine that the korea region extends from 30N to 45N
and from 115W to 135W:
[latlimits,longlimits] = limitm(map,refvec)
latlimits =
30
45
longlimits =
115
135
3 Verify this computation manually by getting the dimensions of the
elevation array and computing the eastern and southern map limits from
the reference vector:
[rows cols] = size(map)
rows =
180
cols =
240
southlat = refvec(2) - rows/refvec(1)
southlat =
30
eastlon = refvec(3) + cols/refvec(1)
eastlon =
135
The results match latlimits(1) and longlimits(2). The two formulas
use different signs because latitudes decrease southwards and longitudes
increase eastward.
2-37
Understanding Map Data
Geographic Interpretation of Matrix Elements
You can access and manipulate gridded geodata and its associated referencing
vector by either geographic or matrix coordinates. Use the russia data set
to explore this. As was demonstrated above, the north, south, east, and west
limits of the mapped area can be determined as follows:
clear; load russia
[latlim,longlim] = limitm(map,refvec)
latlim =
35
80
longlim =
15
190
The data grid in the russia MAT-file extends over the international date
line (180 longitude). You could use the function wrapTo180 to rename the
eastern limit to be -170, or 170W.
The function setltln retrieves the geographic coordinates of a particular
matrix element. The returned coordinates actually show the center of the
geographic area represented by the matrix entry:
row = 23; col = 79;
[lat,long] = setltln(map,refvec,row,col)
lat =
39.5
long =
2-38
Understanding Raster Geodata
30.7
setpostn does the reverse of this, determining the row and column of the data
grid element containing a given geographic point location:
[r,c] = setpostn(map,maplegend,lat,long)
r =
23
c =
79
The Geography of Gridded Geodata
Each matrix element (analogous to a pixel) can be thought of as a spheroidal
quadrangle, which includes its northern and eastern edges, but not its
western edge or southern edge.
East and North edges
are included
West and South edges
are excluded
An Element in a Data Grid
The exceptions to this are that the southernmost row (row 1) also contains its
southern edge, and the westernmost column (column 1) contains its western
edge, except when the map encompasses the entire 360 of longitude. In that
case, the westernmost edge of the first column is not included, because it is
identical to the easternmost edge of the last column. These exceptions ensure
that all points on the globe can be represented exactly once in a regular data
grid.
2-39
Understanding Map Data
Although each data grid element represents an area, not a point, it is often
useful to assign singular coordinates to provide a point of reference. The
setltln function does this. It geolocates an element by the point in the center
of the area represented by the element. The following code references the
center cell coordinate for the row 3, column 17 of the Russia map:
clear; load russia
row = 3; col = 17;
[lat,long] = setltln(map,refvec,row,col)
lat =
35.5
long =
18.3
Because the cells in the russia matrix represent 0.2 squares (5 cells per
degree), the cell in question extends from north of 35.4S to exactly 35.6S,
and from east of 18.2E to exactly 18.4E.
Accessing Data Grid Elements
The actual values contained within the map matrix entries are important as
well. Several Mapping Toolbox functions can access and alter the values
of data grid elements.
If the actual row and column of a desired entry are known, then a simple
matrix index can return the appropriate value:
1 Use the row and column from the previous example (row 3, column 17) to
determine the value of that cell simply by querying the matrix:
value = map(row,col)
value =
2
2 More often, the geographic coordinates are known, and the value can be
retrieved with ltln2val:
value = ltln2val(map,maplegend,lat,long)
2-40
Understanding Raster Geodata
value =
2
3 The latitude-longitude coordinates associated with particular values in a
data grid can be found with findm, analogous to the MATLAB function
find. Here the coordinates of elements in the topo matrix have values
greater than 5,500 meters:
load topo
[lats,longs] = findm(topo>5500,topolegend);
[lats longs]
ans =
34.5000
34.5000
30.5000
28.5000
79.5000
80.5000
84.5000
86.5000
4 To get the row and column indices instead, simply use the Mapping Toolbox
function find:
[i,j]=find(topo>5500)
i =
125
125
121
119
j =
80
81
85
87
5 To recode a specific matrix value to some other value, use changem. Load or
reload the russia MAT-file, and then change all instances of a given value
in a data grid to a new value in one step:
oldcode = ltln2val(map,maplegend,37,79)
oldcode =
2-41
Understanding Map Data
4
newmap = changem(map,5,oldcode);
newcode = ltln2val(newmap,maplegend,37,79)
newcode =
5
All entries in newmap corresponding to 4s in map now have the value 5.
Using a Mask to Recode a Data Grid
You can also define a logical mask to identify the map entries to change. A
mask is a matrix the same size as the map matrix, with 1s everywhere that
values are to change. A mask is often generated by a logical operation on a
map variable, a topic that is described in greater detail below:
1 The russia data grid contains 3 for each cell covering Russia. To set every
non-Russia matrix entry to zero, use the following commands:
clear; load russia
nonrussia = map;
nonrussia(map~=3) = 0;
2 Verify the data that results from these operations:
whos
Name
clrmap
description
map
maplegend
nonrussia
refvec
source
Size
4x3
5x69
225x875
1x3
225x875
1x3
1x68
Bytes
96
690
1575000
24
1575000
24
136
newcode = ltln2val(nonrussia,refvec,37,79)
newcode =
0
2-42
Class
double
char
double
double
double
double
char
Understanding Raster Geodata
Precomputing the Size of a Data Grid
Finally, if you know the latitude and longitude limits of a region, you can
calculate the required matrix size and an appropriate referencing vector
for any desired map resolution and scale. However, before making a large,
memory-taxing data grid, you should first determine what its size will be. For
a map of the continental U.S. at a scale of 10 cells per degree, do the following:
1 Compute the matrix dimensions using sizem, specifying latitude limits of
25N to 50N and longitudes from 60W to 130W:
cellsperdeg = 10;
[r,c,maplegend] = sizem([25 50],[-130 -60],cellsperdeg)
r =
250
c =
700
maplegend =
10
50
-130
msize = r * c * 8
msize =
1400000
This data grid would be 250-by-700, and consume 1,400,000 bytes.
2 Now determine what the storage requirements would be if the scale were
reduced to 5 rows/columns per degree:
cellsperdeg2 = 5;
[r,c,maplegend] = sizem([25 50],[-130 -60],cellsperdeg2)
r =
125
c =
350
maplegend =
5
50
-130
msize = r * c * 8
2-43
Understanding Map Data
msize =
350000
A 125-by-300 matrix that used 350,000 bytes might be more manageable, if it
had sufficient resolution at its intended publication scale.
Geolocated Data Grids
In addition to regular data grids, the toolbox provides another format for
geodata: geolocated data grids. These multivariate data sets can be displayed,
and their values and coordinates can be queried, but unfortunately much of
the functionality supporting regular data grids is not available for geolocated
data grids.
The examples thus far have shown maps that covered simple, regular
quadrangles, that is, geographically rectangular and aligned with parallels
and meridians. Geolocated data grids, in addition to these rectangular
orientations, can have other shapes as well.
Geolocated Grid Format
To define a geolocated data grid, you must define three variables:
A matrix of indices or values associated with the mapped region
A matrix giving cell-by-cell latitude coordinates
A matrix giving cell-by-cell longitude coordinates
The following exercise demonstrates this data representation:
1 Load the MAT-file example of an irregularly shaped geolocated data grid
called mapmtx:
load mapmtx
whos
Name
description
lg1
lg2
2-44
Size
Bytes
Class
1x54
50x50
50x50
108
20000
20000
char
double
double
Attributes
Understanding Raster Geodata
lt1
lt2
map1
map2
source
50x50
50x50
50x50
50x50
1x43
20000
20000
20000
20000
86
double
double
double
double
char
Two geolocated data grids are in this data set, each requiring three
variables. The values contained in map1 correspond to the latitude and
longitude coordinates, respectively, in lt1 and lg1. Notice that all three
matrices are the same size. Similarly, map2, lt2, and lg2 together form a
second geolocated data grid. These data sets were extracted from the topo
data grid shown in previous examples. Neither of these maps is regular,
because their columns do not run north to south.
2 To see their geography, display the grids one after another:
close all
axesm mercator
gridm on
framem on
h1=surfm(lt1,lg1,map1);
h2=surfm(lt2,lg2,map2);
3 Showing coastlines will help to orient you to these skewed grids:
load coast
plotm(lat,long,'r')
2-45
Understanding Map Data
Notice that neither topo matrix is a regular rectangle. One looks like
a diamond geographically, the other like a trapezoid. The trapezoid is
displayed in two pieces because it crosses the edge of the map. These
shapes can be thought of as the geographic organization of the data, just as
rectangles are for regular data grids. But, just as for regular data grids,
this organizational logic does not mean that displays of these maps are
necessarily a specific shape.
4 Now change the view to a polyconic projection with an origin at 0N, 90E:
setm(gca,'MapProjection','polycon', 'Origin',[0 90 0])
2-46
Understanding Raster Geodata
As the polyconic projection is limited to a 150 range in longitude, those
portions of the maps outside this region are automatically trimmed.
Geographic Interpretations of Geolocated Grids
Mapping Toolbox software supports three different interpretations of
geolocated data grids:
First, a map matrix having the same number of rows and columns as the
latitude and longitude coordinate matrices represents the values of the
map data at the corresponding geographic points (centers of data cells).
Next, a map matrix having one fewer row and one fewer column than the
geographic coordinate matrices represents the values of the map data
within the area formed by the four adjacent latitudes and longitudes.
2-47
Understanding Map Data
Finally, if the latitude and longitude matrices have smaller dimensions
than the map matrix, you can interpret them as describing a coarser
graticule, or mesh of latitude and longitude cells, into which the blocks of
map data are warped.
This section discusses the first two interpretations of geolocated data grids.
For more information on the use of graticules, see The Map Grid on page
4-53.
Type 1: Values associated with upper left grid coordinate. As an
example of the first interpretation, consider a 4-by-4 map matrix whose cell
size is 30-by-30 degrees, along with its corresponding 4-by-4 latitude and
longitude matrices:
map = [ 1 2 3
5 6 7 8;...
9 10 11 12;...
3 14 15 16];
4;...
lat = [ 30 30 30 30;...
0
0
0
0;...
-30 -30 -30 -30;...
-60 -60 -60 -60];
long = [0 30 60 90;...
0 30 60 90;...
0 30 60 90;...
0 30 60 90];
This geolocated data grid is displayed with the values of map shown at the
associated latitudes and longitudes.
2-48
Understanding Raster Geodata
Notice that only 9 of the 16 total cells are displayed. The value displayed for
each cell is the value at the upper left corner of that cell, whose coordinates
are given by the corresponding lat and long elements. By convention, the
last row and column of the map matrix are not displayed, although they exist
in the CData property of the surface object.
Type 2: Values centered within four adjacent coordinates. For the
second interpretation, consider a 3-by-3 map matrix with the same lat and
long variables:
map = [1 2 3;...
4 5 6;...
7 8 9];
Here is a surface plot of the map matrix, with the values of map shown at the
center of the associated cells:
2-49
Understanding Map Data
All the map data is displayed for this geolocated data grid. The value of each
cell is the value at the center of the cell, and the latitudes and longitudes in
the coordinate matrices are the boundaries for the cells.
Ordering of Cells. You may have noticed that the first row of the matrix is
displayed as the top of the map, whereas for a regular data grid, the opposite
was true: the first row corresponded to the bottom of the map. This difference
is entirely due to how the lat and long matrices are ordered. In a geolocated
data grid, the order of values in the two coordinate matrices determines the
arrangement of the displayed values.
Transforming Regular to Geolocated Grids. When required, a regular
data grid can be transformed into a geolocated data grid. This simply requires
that a pair of coordinates matrices be computed at the desired spatial
resolution from the regular grid. Do this with the meshgrat function, as
follows:
load topo
[lat,lon] = meshgrat(topo,topolegend);
Name
Size
Bytes
lat
lon
topo
topolegend
topomap1
topomap2
2-50
180x360
180x360
180x360
1x3
64x3
128x3
518400
518400
518400
24
1536
3072
Class
double
double
double
double
double
double
Attributes
Understanding Raster Geodata
Transforming Geolocated to Regular Grids. Conversely, a regular data
grid can also be constructed from a geolocated data grid. The coordinates
and values can be embedded in a new regular data grid. The function that
performs this conversion is geoloc2grid; it takes a geolocated data grid and
a cell size as inputs.
2-51
Understanding Map Data
Reading and Writing Geospatial Data
In this section...
Functions that Read and Write Geospatial Data on page 2-52
Exporting Vector Geodata on page 2-57
Functions That Read and Write Files in Compressed Formats on page 2-67
Functions that Read and Write Geospatial Data
Many vector and raster data formats have been developed for storing
geospatial data in computer files. Some formats are widely used, others are
obscure; some are simple, while others are elaborate. Some formats are
government or international standards, others are simply popular. A format
can be general-purpose, specific to a narrow class of data, or may be used just
to publish a certain data set.
Using Mapping Toolbox functions, you can read geodata files in generic
exchange formats (e.g., SDTS, shapefiles, and GeoTIFF files) that a variety
of mapping and image processing applications can also read and write. You
can also read files that are in special formats designed to exchange specific
sets of geodata (e.g., AVHRR, GSHHS, DCW, DEM, and DTED files). You can
order, and in some cases download, such data over the Internet from public
agencies and private distributors.
In addition, the toolbox provides generalized sample data in the form of data
files for the entire Earth and its major regions, as well as some more detailed
demo geodata files covering small areas. These data sets, which are located in
matlabroot/toolbox/map/mapdemos, are used in most of the code examples
provided in this documentation. Many of the sample data sets are described
in text files also located in that directory.
If you need to locate geospatial data in particular formats, or
for specific themes or regions, you can consult the following
MathWorks Tech Note 2101, which is regularly updated.
http://www.mathworks.com/support/tech-notes/2100/2101.html
The following table lists Mapping Toolbox functions that read geospatial
data products and file formats and write geospatial data files. Note that the
2-52
Reading and Writing Geospatial Data
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
2-53
Understanding Map Data
Function
Description
Type of Data
Type of
Coordinates
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 ETOPO2 or ETOPO5
(2-minute or 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 a GeoTIFF file
properties
map
geo
2-54
geotiffread
Read a georeferenced image from
GeoTIFF file
image
map
getworldfilename
Derive a worldfile name from an
image filename
filename
geo
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
map
Reading and Writing Geospatial Data
Function
Description
Type of Data
Type of
Coordinates
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
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
Read geographic feature coordinates
and associated attributes from a
shapefile
vector
Write geospatial data and associated
attributes in shapefile format
vector
shaperead
shapewrite
map
map
geo
map
geo
map
2-55
Understanding Map Data
Function
Description
Type of Data
Type of
Coordinates
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 geo
information
worldfilewrite
Export a referencing matrix into an
equivalent worldfile
georeferencing geo
information
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
demos Creating a Half-Resolution Georeferenced Image and Georeferencing
an Image to an Orthotile Base Layer for examples of how you can do this.
2-56
Reading and Writing Geospatial Data
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
Geostructs and Mapstructs on page 2-20 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
2-57
Understanding Map Data
placemark. (However, the users of an Earth browser can generally control
their views of it).
Generating A Single Placemark. Here is a placemark produced by
kmlwrite that locates the headquarters of The MathWorks, as displayed in
the Google Earth application.
The location, text, and icon for the placemark were specified to kmlwrite as
follows:
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;
2-58
Reading and Writing Geospatial Data
filename = 'The_MathWorks.kml';
kmlwrite(filename, lat, lon, ...
'Description', description, 'Name', name, ...
'Icon', iconFilename, 'IconScale', iconScale);
The file produced by kmlwrite looks like this:
<?xml version="1.0" encoding="utf-8"?>
<kml xmlns="http://earth.google.com/kml/2.1">
<Document>
<name>The_MathWorks</name>
<Placemark>
<Snippet maxLines="0"> </Snippet>
<description>3 Apple Hill Drive&lt;br>Natick, MA. 01760&lt;/b>
&lt;br>http://www.mathworks.com&lt;/b>
</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.
2-59
Understanding Map Data
Placemarks from Addresses. You do not need coordinates in order to
geolocate placemarks; instead, you can specify street addresses or more
general addresses such as postal codes, city, state, or country names in a
KML file. (Note that the Google Maps service does not support address-based
placemarks.) If the viewing application is capable of looking up addresses,
such placemarks can be displayed in appropriate, although possibly imprecise,
locations. 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://earth.google.com/kml/2.1">
<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>
2-60
Reading and Writing Geospatial Data
</Placemark>
</Document>
</kml>
The placemarks display in a Google Earth map like this, with default
placemark icons.
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 demo 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.
2-61
Understanding Map Data
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';
2-62
Reading and Writing Geospatial Data
kmlwrite(kmlfilename,tsunamis);
3 View the placemarks in an earth browser
On Windows, use winopen to open Google Earth (which must be installed)
to view the KML file.
winopen(kmlfilename)
On Macintosh or Linux platforms, use the system command to launch
Google Earth.
cmd = 'googleearth ';
fullfilename = fullfile(pwd, filename);
system([cmd fullfilename])
Rotate to the Western Pacific ocean and zoom to inspect the placemarks.
Click on the pushpin icons to see the attribute table for any event.
kmlwrite formats tables by default to display all the attributes in the
geostruct passed to it.
2-63
Understanding Map Data
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:
Cause:
Year:
Location:
Country:
2-64
[1x1
[1x1
[1x1
[1x1
[1x1
struct]
struct]
struct]
struct]
struct]
Reading and Writing Geospatial Data
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);
Refresh the earth browser to display the new version of the KML file.
2-65
Understanding Map Data
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));
2-66
Reading and Writing Geospatial Data
kmlwrite(kmlfilename,tsunamis,'Description',attribspec,...
'Name',{tsunamis.Location},'Icon',iconname,...
'IconScale',loghgte);
Refresh the earth browser to display the new version of the KML file.
Position the viewpoint to compare with the previous view of the Pacific
region. Diameters of placemarks now correspond to log(Max_Height).
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
2-67
Understanding Map Data
functions read or write such files. All create files in a directory 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 functions 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.
2-68
3
Understanding Geospatial
Geometry
Understanding Spherical Coordinates on page 3-2
Understanding Latitude and Longitude on page 3-11
Understanding Angles, Directions, and Distances on page 3-14
Understanding Map Projections on page 3-29
Great Circles, Rhumb Lines, and Small Circles on page 3-32
Directions and Areas on the Sphere and Spheroid on page 3-38
Planetary Almanac Data on page 3-46
See Chapter 2, Understanding Map Data for information on how geographic
phenomena are encoded and represented numerically, and how geodata
is structured.
Understanding Geospatial Geometry
Understanding Spherical Coordinates
In this section...
Spheres, Spheroids, and Geoids on page 3-2
Geoid and Ellipsoid on page 3-2
The Ellipsoid Vector on page 3-4
Spheres, Spheroids, and Geoids
Working with geospatial data involves geographic concepts (e.g., geographic
and plane coordinates, spherical geometry) and geodetic concepts (such as
ellipsoids and datums). This group of sections explain, at a high level, some of
the concepts that underlie geometric computations on spherical surfaces.
Although the Earth is very round, it is an oblate spheroid rather than
a perfect sphere. This difference is so small (only one part in 300) that
modeling the Earth as spherical is sufficient for making small-scale (world or
continental) maps. However, making accurate maps at larger scale demands
that a spheroidal model be used. Such models are essential, for example,
when you are mapping high-resolution satellite or aerial imagery, or when
you are working with coordinates from the Global Positioning System (GPS).
This section addresses how Mapping Toolbox software accurately models the
shape, or figure, of the Earth and other planets.
Geoid and Ellipsoid
Literally, geoid means Earth-shaped. The geoid is an empirical approximation
of the figure of the Earth (minus topographic relief), its lumpiness..
Specifically, it is an equipotential surface with respect to gravity, more or less
corresponding to mean sea level. It is approximately an oblate ellipsoid, but
not exactly so because local variations in gravity create minor hills and dales
(which range from -100 m to +60 m across the Earth). This variation in height
is on the order of one percent of the differences between the semimajor and
semiminor ellipsoid axes used to approximate the Earths shape, as described
in The Ellipsoid Vector on page 3-4.
3-2
Understanding Spherical Coordinates
Mapping the Geoid
The following figure, made using the geoid data set, maps the figure of the
Earth. To execute these commands, select them all by dragging over the list
in the Help browser, then click the right mouse button and choose Evaluate
Selection:
load geoid; load coast
figure; axesm robinson
geoshow(geoid,geoidlegend,'DisplayType','texturemap')
colorbar('horiz')
geoshow(lat,long,'color','k')
The shape of the geoid is important for some purposes, such as calculating
satellite orbits, but need not be taken into account for every mapping
application. However, knowledge of the geoid is sometimes necessary, for
example, when you compare elevations given as height above mean sea level
to elevations derived from GPS measurements. Geoid representations are
also inherent in datum definitions.
3-3
Understanding Geospatial Geometry
You can define ellipsoids in several ways. They are usually specified by
a semimajor and a semiminor axis, but are often expressed in terms of
a semimajor axis and either inverse flattening (which for the Earth, as
mentioned above, is one part in 300) or eccentricity. Whichever parameters are
used, as long as an axis length is included, the ellipsoid is fully constrained
and the other parameters are derivable. The components of an ellipsoid are
shown in the following diagram.
Semiminor
(polar)
axis
Semimajor
(equatorial)
axis
Axis of rotation
The toolbox includes ellipsoid models that represent the figures of the Sun,
Moon, and planets, as well as a set of the most common ellipsoid models of
the Earth.
The Ellipsoid Vector
Mapping Toolbox Ellipsoid Management on page 3-7
Functions that Define Ellipsoid Vectors on page 3-9
What Is the Correct Ellipsoid Vector? on page 3-9
3-4
Understanding Spherical Coordinates
Mapping Toolbox ellipsoid representations are two-element vectors, called
ellipsoid vectors. The ellipsoid vector has the form [semimajor_axis
eccentricity]. The semimajor axis can be in any unit of distance; the choice
of units typically drives the units used for distance outputs in the toolbox
functions. Meters, kilometers, or Earth radii (i.e., a unit sphere) are most
frequently used. See Functions that Define Ellipsoid Vectors on page 3-9 for
details.
Eccentricity can range from 0 to 1. Most toolbox functions accept a scalar in
place of an ellipsoid vector. In this case, its value is interpreted as the radius
of a reference sphere, which is equivalent to an ellipsoid with an eccentricity
of zero.
Standard values for the ellipsoid vector, along with several other kinds of
planetary data for each of the planets and the Earths moon, are provided by
the Mapping Toolbox almanac function (see Planetary Almanac Data on
page 3-46). In the almanac function, the default ellipsoid for the Earth is the
1980 Geodetic Reference System ellipsoid:
format long g
almanac('earth','ellipsoid','kilometers')
ans =
6378.137
0.0818191910428158
Compare this to a spherical ellipsoid definition:
almanac('earth','sphere','kilometers')
ans =
6371
You should set format to long g, as above, if you want to display eccentricity
values at full precision.
For example, examine the parameters of the wgs72 (the 1972 World Geodetic
System) ellipsoid, using the almanac function:
wgs72 = almanac('earth','wgs72','kilometers')
wgs72 =
3-5
Understanding Geospatial Geometry
6378.135
0.0818188106627487
Compare this with Bessels 1841 ellipsoid:
format long g
bessel = almanac('earth','bessel','kilometers')
bessel =
6377.397155
0.0816968312225275
The ellipsoid vectors values are the semimajor axis, in kilometers, and
eccentricity. Both eccentricity and flattening are dimensionless ratios.
The toolbox has functions to convert elliptical definitions from these forms
to ellipsoid vector form. For example, the function axes2ecc returns an
eccentricity when given semimajor and semiminor axes as arguments.
The ellipse in the previous diagram is highly exaggerated. For the Earth, the
semimajor axis is about 21 kilometers longer than the semiminor axis. Use
the almanac function to verify this:
grs80 = almanac('earth','ellipsoid','kilometers')
grs80 =
6378.137
0.0818191910428158
semiminor = minaxis(grs80)
semiminor =
6356.75231414036
semidiff = grs80(1) - semiminor
semidiff =
21.3846858596444
When compared to the semimajor axis, which is almost 6400 kilometers,
this difference seems insignificant and can be neglected for world and other
small-scale maps. For example, the scale at which 21.38 km would be smaller
than a 0.5 mm line on a map (which is a typical line weight in cartography) is
kmtomm = unitsratio('mm','km')
3-6
Understanding Spherical Coordinates
kmtomm =
1000000
scalelim = semidiff * kmtomm / 0.5
scalelim =
4.2769e+007
The unitsratio function was used to convert the distance semidiff from
kilometers into millimeters. This indicates that the Earths eccentricity is not
geometrically meaningful at scales of less than 1:43,000,000, which is roughly
the scale of a world map shown on a page of this document. Consequently,
most Mapping Toolbox functions default to a spherical model of the Earth.
Another reason for defaulting to a sphere is that angular distances are not
meaningful on ellipsoids, and some Mapping Toolbox functions compute or
use angular distances. See Working with Distances on the Sphere on page
3-23 for more information. Regardless, you are free to specify any ellipsoid
when you define map axes or otherwise operate on geodata.
Mapping Toolbox Ellipsoid Management
Most maps you make with the toolbox are displayed in a map axes, which is
a MATLAB axes that contains a key data structure called a map projection
structure, or mstruct. A reference ellipsoid is fundamental to defining a map
axes, and is stored in the geoid field of the mstruct. (The geographic term
geoid actually refers to a model of the shape of the earth that is much more
detailed. See Geoid and Ellipsoid on page 3-2 for more information.) Other
mstruct fields specify parameters that define the map axes current projection
and for controlling the appearance of the map frame, grid, and grid labels.
You define an mstruct with the axesm or defaultm functions. See Map Axes
Object Properties on page 12-36 for definitions of the fields found in mstructs.
You can pass an mstruct to certain functions you call. Other functions obtain
the mstruct from the current map axes. (If it is not a map axes, such functions
error.) When axesm or defaultm create a map axes containing an mstruct,
their default behavior is to use a unit sphere for the ellipsoid vector. Unless
you override this default, you must work in units of earth radii (or radii of
whatever planet you are mapping). The following short example shows this
clearly (getm obtains mstruct parameters from a map axes):
3-7
Understanding Geospatial Geometry
worldmap australia
ellipsoid = getm(gca,'geoid')
ans =
1
The worldmap function chooses map projections and parameters appropriate
to the region specified to it and sets up default values for the rest of the
mstruct. The geoid parameter is the ellipsoid vector that worldmap generated.
The first element of the output vector indicates that the semimajor axis has
a length of 1; the second element indicates that there is no eccentricity.
Therefore, you are working with a spherea unit sphere, to be specific.
If, instead of using default ellipsoid vectors, you prefer to be explicit about
your reference ellipsoid, then you can work in the length units of your choice,
on either a sphere or an ellipsoid. In following example (on the sphere),
axesm('mapprojection','mercator',...
'geoid',almanac('earth','radius','meters'))
[x, y] = mfwdtran(0,90)
x =
1.0008e+07
y =
0
the projected map coordinates for a point at 0 degrees latitude, 90 degrees
longitude falls just over 107 meters east of the origin. If you then revert to a
unit sphere (the default ellipsoid), the distance units are quite different:
axesm mercator
[x, y] = mfwdtran(0,90)
x =
1.5708
y =
0
This value for x turns out to equal /2, which might tempt you to think that
the Mercator projection has simply converted degrees to radians. But what
has actually changed is that the point at (0, 90) now maps to a point 1 earth
3-8
Understanding Spherical Coordinates
radius east of the origin. Because Mercator is a cylindrical projection having
no length distortion along the equator, and because a radian is defined in
terms of a spheres radius, the numbers just happen to work out this way.
Functions that Define Ellipsoid Vectors
Some functions define a radius or an ellipsoid and can make different choices
when doing so. In addition to axesm and defaultm, which create mstructs
with ellipsoid vectors that default to a unit sphere, the following functions
have default ellipsoid vectors or radii:
The elevation Function. The elevation function uses the GRS 80 ellipsoid
in meters as its default; unless you specify a reference ellipsoid vector
yourself, elevation will assume that input altitudes and the output slant
range are both in units of meters.
The distance and reckon Functions. These functions assume by default
a reference sphere with a radius of 1 (a unit sphere), but scale their range
inputs and outputs to equal the size (in degrees) of the angle subtended by
rays joining the center of the Earth (or planet) to the start and end points.
To obtain results on an ellipsoid you must specify an ellipsoid vector such
as almanac provides.
Angle-Distance Conversion Functions. The default behavior of the 12
angle-distance conversion utilities (itemized in Working with Distances on
the Sphere on page 3-23) is different than the above; as discussed below,
these functions assume a sphere with a radius of 6371 kilometers (or,
equivalently, 3440.065 nautical miles or 3958.748 statute miles), which is a
reasonable average radius for Earth.
See the documentation for individual functions if you are not clear whether or
how they may generate default reference ellipsoids.
What Is the Correct Ellipsoid Vector?
Many different reference ellipsoids have been proposed through the years.
They differ because of the surveying information upon which they are based,
or because they are intended to approximate the Earth only within a specific
geographic region. In many cases you will want to use either the Geodetic
Referencing System of 1980 (GRS80) ellipsoid or the World Geodetic System
3-9
Understanding Geospatial Geometry
1984 (WGS84); their semimajor axis lengths are equal and their semiminor
axes (i.e., center to pole) differ in length by just over 1/10 mm, as the following
code demonstrates:
grs80 = almanac('earth','grs80','meters');
wgs84 = almanac('earth','wgs84','meters');
minaxis(wgs84) - minaxis(grs80)
ans =
1.0482e-004
The toolbox supports several other ellipsoid vectors, for models ranging from
Everests 1830 ellipsoid (used for India) to the International Astronomical
Union ellipsoid of 1965 (used for Australia). These can be referenced by the
following statements:
ellipsoid1 = almanac('earth','ellipsoid','kilometers','everest');
ellipsoid2 = almanac('earth','ellipsoid','kilometers','iau65');
See the reference page for the almanac function for more information on the
ellipsoids that are built into the toolbox. If you cannot find the ellipsoid vector
you need, you can create it in the following form:
ellipsoidvec = [semimajor_axis eccentricity]
3-10
Understanding Latitude and Longitude
Understanding Latitude and Longitude
Two angles, latitude and longitude, specify the position of a point on the
surface of a planet. These angles can be in degrees or radians; however,
degrees are far more common in geographic notation.
Latitude is the angle between the plane of the equator and a line connecting
the point in question to the planets rotational axis. There are different ways
to construct such lines, corresponding to different types of and resulting values
for latitudes. Latitude is positive in the northern hemisphere, reaching a limit
of +90 at the north pole, and negative in the southern hemisphere, reaching a
limit of -90 at the south pole. Lines of constant latitude are called parallels.
This system is depicted in the following figure, commands for which are
load coast
axesm('ortho','origin',[45 45]); axis off;
gridm on; framem on;
mlabel('equator')
plabel(0); plabel('fontweight','bold')
plotm(lat, long)
3-11
Understanding Geospatial Geometry
Longitude is the angle at the center of the planet between two planes that
align with and intersect along the axis of rotation, perpendicular to the plane
of the equator. One plane passes through the surface point in question, and
the other plane is the prime meridian (0 longitude), which is defined by the
location of the Royal Observatory in Greenwich, England. Lines of constant
longitude are called meridians. All meridians converge at the north and south
poles (90N and -90S), and consequently longitude is under-specified in
those two places.
Longitudes typically range from -180 to +180, but other ranges can be used,
such as 0 to +360. Longitudes can also be specified as east of Greenwich
(positive) and west of Greenwich (negative). Adding or subtracting 360 from
its longitude does not alter the position of a point. The toolbox includes a set
of functions (wrapTo180, wrapTo360, wrapToPi, and wrapTo2Pi) that convert
longitudes from one range to another. It also provides unwrapMultipart,
which unwraps vectors of longitudes in radians by removing the artifical
3-12
Understanding Latitude and Longitude
discontinuities that result from forcing all values to lie within some 360-wide
interval.
3-13
Understanding Geospatial Geometry
Understanding Angles, Directions, and Distances
In this section...
Positions, Azimuths, Headings, Distances, Length, and Ranges on page
3-14
Working with Length and Distance Units on page 3-15
Working with Angles: Units and Representations on page 3-18
Working with Distances on the Sphere on page 3-23
Angles as Binary and Formatted Numbers on page 3-27
Positions, Azimuths, Headings, Distances, Length,
and Ranges
When using spherical coordinates, distances are expressed as angles, not
lengths. As there is an infinity of arcs that can connect two points on a sphere
or spheroid, by convention the shortest one (the great circle distance) is used
to measure how close two points are. As is explained in Working with
Distances on the Sphere on page 3-23, you can convert angular distance on
a sphere to linear distance. This is different from working on an ellipsoid,
where one can only speak of linear distances between points, and to compute
them one must specify which reference ellipsoid to use.
In spherical or geodetic coordinates, a position is a latitude taken together
with a longitude, e.g., (lat,lon), which defines the horizontal coordinates
of a point on the surface of a planet. When we consider two points,
e.g.,(lat1,lon1) and (lat2,lon2), there are several ways in which their
2D spatial relationships are typically quantified:
The azimuth (also called heading) to take to get from (lat1,lon1) to
(lat2,lon2)
The back azimuth (also called heading) from (lat2,lon2) to (lat1,lon1)
The spherical distance separating (lat1,lon1) from (lat2,lon2)
The linear distance (range) separating (lat1,lon1) from (lat2,lon2)
3-14
Understanding Angles, Directions, and Distances
The first three are angular quantities, while the last is a length. Mapping
Toolbox functions exist for computing these quantities. For more information,
see Directions and Areas on the Sphere and Spheroid on page 3-38 and also
Navigation on page 10-11 for additional examples.
There is no single default unit of distance measurement in the toolbox.
Navigation functions use nautical miles as a default, the almanac function
uses kilometers, and the distance function uses degrees of arc length. For
many functions, the default unit for distances and positions is degrees, but
you need to verify the default assumptions before using any of these functions.
Note When distances are given in terms of angular units (degrees or radians),
be careful to remember that these are specified in terms of arc length. While a
degree of latitude always subtends one degree of arc length, this is only true
for degrees of longitude along the equator.
Working with Length and Distance Units
Choosing Units of Length on page 3-16
Converting Units of Length on page 3-16
Computing Conversion Factors on page 3-17
Linear measurements of lengths and distances on spheres and spheroids
can use the same units they do on the plane, such as feet, meters, miles,
and kilometers. They can be used for
Absolute positions, such as map coordinates or terrain elevations
Dimensions, such as a planets radius or its semimajor and semiminor axes
Distances between points or along routes, in 2-D or 3-D space or across
terrain
Length units are needed to describe
The dimensions of a reference sphere or ellipsoid
The line-of-sight distance between points
3-15
Understanding Geospatial Geometry
Distances along great circle or rhumb line curves on an ellipsoid or sphere
X-Y locations in a projected coordinate system or map grid
Offsets from a map origin (false eastings and northings)
X-Y-Z locations in Earth-centered Earth-fixed (ECEF) or local vertical
systems
Heights of various types (terrain elevations above a geoid, an ellipsoid,
or other reference surface
Choosing Units of Length
Using the toolbox effectively depends on being consistent about units of
length. Depending on the specific function and the way you are calling it,
when you specify lengths, you could be
Explicitly specifying a radius or reference ellipsoid vector
Relying on the function itself to specify a default radius or ellipsoid
Relying on the reference ellipsoid associated with a map projection
structure (mstruct)
Whenever you are doing a computation that involves a reference sphere or
ellipsoid, make sure that the units of length you are using are the same units
used to define the radius of the sphere or semimajor axis of the ellipsoid.
These considerations are discussed below.
Converting Units of Length
The following Mapping Toolbox functions convert between different units
of length:
unitsratio computes multiplicative factors for converting between 12
different units of length as well as between degrees and radians. You
can use unistratio to perform conversions when neither the input units
of length nor the output units of length are known until run time. See
Converting Angle Units that Vary at Run Time on page 3-22 for more
information.
3-16
Understanding Angles, Directions, and Distances
km2nm, km2sm, nm2km, nm2sm, sm2km, and sm2nm perform simple and
convenient conversions between kilometers, nautical miles, and statute
miles.
These utility functions accept scalars, vectors, and matrices, or any shape. For
an overview of these functions and angle conversion functions, see Summary:
Available Distance and Angle Conversion Functions on page 3-26.
Computing Conversion Factors
The unitsratio function can compute the ratio between any of the following
units of length:
Microns
Millimeters
Centimeters
Meters
Kilometers
Inches
International feet
U.S. survey feet
Yards
International miles
U.S. survey (statute) miles
The syntax for unitsratio is
ratio = unitsratio(to-unit,from-unit)
You can use the output from unitsratio as a multiplicative conversion factor.
1 For example, the following shows that 4 inches span just over 10
centimeters:
cmPerInch = unitsratio('cm','inch')
cm = cmPerInch * 4
3-17
Understanding Geospatial Geometry
cmPerInch =
2.5400
cm =
10.16
2 To convert this number of centimeters back to inches, type
inch = unitsratio('in','centimeter') * cmPerInch
inch =
1
Note that unitsratio supports various abbreviations for units of length.
The unitsratio function also lets you convert angles between degrees and
radians.
Working with Angles: Units and Representations
Radians and Degrees on page 3-19
Default and Variable Angle Units on page 3-20
Degrees, Minutes, and Seconds on page 3-20
Converting Angle Units that Vary at Run Time on page 3-22
Angular measurements have many distinct roles in geospatial data handling.
For example, they are used to specify
Absolute positions latitudes and longitudes
Relative positions azimuths, bearings, and elevation angles
Spherical distances between point locations
Absolute positions are expressed in geodetic coordinates, which are actually
angles between lines or planes on a reference sphere or ellipsoid. Relative
positions use units of angle to express the direction between one place on
the reference body from another one. Spherical distances quantify how far
3-18
Understanding Angles, Directions, and Distances
two places are from one another in terms of the angle subtended along a
great-circle arc. On nonspherical reference bodies, distances are usually given
in linear units such as kilometers (because on them, arc lengths are no longer
proportional to subtended angle).
Radians and Degrees
The basic unit for angles in MATLAB is the radian. For example, if the
variable theta represents an angle and you want to take its sine, you can
use sin(theta) if and only if the value of theta is expressed in radians. If a
variable represents the value of an angle in degrees, then you must convert
the value to radians before taking the sine. For example,
thetaInDegrees = 30;
thetaInRadians = thetaInDegrees * (pi/180)
sinTheta = sin(thetaInRadians)
As shown above, you can scale degrees to radians by multiplying by pi/180.
However, you should consider using the Mapping Toolbox function degtorad
for this purpose:
thetaInRadians = degtorad(thetaInDegrees)
Likewise, you can perform the opposite conversion by applying the inverse
factor,
thetaInDegrees = thetaInRadians * (180/pi)
or by using radtodeg,
thetaInDegrees = radtodeg(thetaInRadians)
The practice of using these functions has two significant advantages:
It reduces the likelihood of human error (e.g., you might type pi/108 by
mistake)
It signals clearly your intentimportant to do should others ever read,
modify, or debug your code
The functions radtodeg and degtorad are very simple and efficient, and
operate on vector and higher-dimensioned input as well as scalars.
3-19
Understanding Geospatial Geometry
Default and Variable Angle Units
Unlike MATLAB trigonometric functions, Mapping Toolbox functions do not
always assume that angular arguments are in units of radians.
The low-level utility functions intended as building blocks of more complex
features or applications work only in units of radians. Examples include the
functions unwrapMultipart and meridianarc.
Many high-level functions, including distance, can work in either degrees
or radians. Their interpretation of angles is controlled by a string-valued
'angleunits' input argument. (angleunits can be either 'degrees' or
'radians', and can generally be abbreviated.) This flexibility balances
convenience and efficiency, although it means that you must take care to
check what assumptions each function is making about its inputs.
Degrees, Minutes, and Seconds
In all Mapping Toolbox computations that involve angles in degrees,
floating-point numbers (generally MATLAB class double) are used, which
allows for integer and fractional values and rational approximations to
irrational numbers. However, several traditional notations, which are still in
wide use, represent angles as pairs or triplets of numbers, using minutes of
arc (1/60 of degree) and seconds of arc (1/60 of a minute):
Degrees-minutes notation (DM), e.g., 35 15, equal to 35.25
Degrees-minutes-seconds notation (DMS) , e.g., 35 15 45, equal to
35.2625
In degrees-minutes representation, an angle is split into three separate parts:
1 A sign
2 A nonnegative, integer-valued degrees component
3 A nonnegative minutes component, real-valued and in the half-open
interval [0 60)
For example, -1 radians is represented by a minus sign (-) and the numbers
[57, 17.7468...]. (The fraction in the minutes part approximates an irrational
3-20
Understanding Angles, Directions, and Distances
number and is rounded here for display purposes. This subtle point is
revisited in the following section.)
The toolbox includes the function degrees2dm to perform conversions of this
sort. You can use this function to export data in DM form, either for display
purposes or for use by another application. For example,
degrees2dm(radtodeg(-1))
ans =
-57.0000
17.7468
More generally, degrees2dm converts a single-columned input to a pair of
columns. Rather than storing the sign in a separate element, degrees2dm
applies to the first nonzero element in each row. Function dm2degrees
converts in the opposite direction, producing a real-valued column vector of
degrees from a two-column array having an integer degrees and real-valued
minutes column. Thus,
dm2degrees(degrees2dm(pi)) == pi
ans =
1
Similarly, in degrees-minutes-seconds representation, an angle is split into
four separate parts:
1 A sign
2 A nonnegative integer-valued degrees component
3 A minutes component which can be any integer from 0 through 59
4 A nonnegative minutes component, real-valued and in the half-open
interval [0 60)
For example, -1 radians is represented by a minus sign (-) and the numbers
[57, 17, 44.8062...], which can be seen using Mapping Toolbox function
degrees2dms,
3-21
Understanding Geospatial Geometry
degrees2dms(radtodeg(-1))
ans =
-57.0000
17.0000
44.8062
degrees2dms works like degrees2dm; it converts single-columned input to
three-column form, applying the sign to the first nonzero element in each row.
A fourth function, dms2degrees, is similar to dm2degrees and supports data
import by producing a real-valued column vector of degrees from an array
with an integer-valued degrees column, an integer-value minutes column, and
a real-valued seconds column. As noted, the four functions, degrees2dm,
degrees2dms, dm2degrees, and dms2degrees, are particular about the shape
of their inputs; in this regard they are distinct from the other angle-conversion
functions in the toolbox.
The toolbox makes no internal use of DM or DMS representation. The
conversion functions dm2degrees and dms2degrees are provided only as
tools for data import. Likewise, degrees2dm and degrees2dms are only
useful for displaying geographic coordinates on maps, publishing coordinate
values, and for formatting data to be exported to other applications. Methods
for accomplishing this are discussed below, in Formatting Latitudes and
Longitudes as Strings on page 3-28.
Converting Angle Units that Vary at Run Time
Functions degtorad and radtodeg are simple to use and efficient, but how do
you write code to convert angles if you do not know ahead of time what units
the data will use? The toolbox provides a set of utility functions that help you
deal with such situations at run time.
In almost all caseseven at the time you are codingyou know either the
input or destination angle units. When you do, you can use one of these
functions:
fromDegrees
toDegrees
fromRadians
toRadians
3-22
Understanding Angles, Directions, and Distances
For example, you might wish to implement a very simple sinusoidal projection
on the unit sphere, but allow the input latitudes and longitudes to be in either
degrees or radians. You can accomplish this as follows:
function [x, y] = sinusoidal(lat, lon, angleunits)
[lat, lon] = toRadians(angleunits, lat, lon);
x = lon .* cos(lat);
y = lat;
Whenever angleunits turns out to be 'radians' at run time, the toRadians
function has no real work to do; all the functions in this group handle such
no-op situations efficiently.
In the very rare instances when you must code an application or MATLAB
function in which the units of both input angles and output angles remain
unknown until run time, you can still accomplish the conversion by using the
unitsratio function. For example,
fromUnits = 'radians';
toUnits = 'degrees';
piInDegrees = unitsratio(toUnits, fromUnits) * pi
piInDegrees =
180
Working with Distances on the Sphere
Examples of Spherical-Linear Distance Conversions on page 3-25
Range as an Angle in the distance and reckon Functions on page 3-26
Summary: Available Distance and Angle Conversion Functions on page
3-26
Many geospatial domains (seismology, for example) describe distances
between points on the surface of the earth as angles. This is simply the result
of dividing the length of the shortest great-circle arc connecting a pair points
by the radius of the Earth (or whatever planet one is measuring). This gives
the angle (in radians) subtended by rays from each point that join at the
center of the Earth (or other planet). This is sometimes called a spherical
distance. You can thus call the resulting number a distance in radians. You
3-23
Understanding Geospatial Geometry
could also call the same number a distance in earth radii. When you work
with transformations of geodata, keep this in mind.
You can easily convert that angle from radians to degrees. For example, you
can call distance to compute the distance in meters from London to Kuala
Lumpur:
latL = 51.5188;
lonL = -0.1300;
latK =
2.9519;
lonK = 101.8200;
earthRadiusInMeters = 6371000;
distInMeters = distance(latL, lonL,...
latK, lonK, earthRadiusInMeters)
distInMeters =
1.0571e+007
Then convert the result to an angle in radians:
distInRadians = distInMeters / earthRadiusInMeters
distInRadians =
1.6593
Finally, convert to an angle in degrees:
distInDegrees = radtodeg(distInRadians)
distInDegrees =
95.0692
This really only makes sense and produces accurate results when we
approximate the Earth (or planet) as a sphere. On an ellipsoid, one can only
describe the distance along a geodesic curve using a unit of length.
Mapping Toolbox software includes a set of six functions to conveniently
convert distances along the surface of the Earth (or another planet) from
units of kilometers (km), nautical miles (nm), or statue miles (sm) to spherical
distances in degrees (deg) or radians (rad):
3-24
Understanding Angles, Directions, and Distances
km2deg, nm2deg, and sm2deg go from length to angle in degrees
km2rad, nm2rad, and sm2rad go from length to angle in radians
You could replace the final two steps in the preceding example with
distInKilometers = distInMeters/1000;
earthRadiusInKm = 6371;
km2deg(distInKilometers, earthRadiusInKm)
ans =
95.0692
Because these conversion can be reversed, the toolbox includes another six
convenience functions that convert an angle subtended at the center of a
sphere, in degrees or radians, to a great-circle distance along the surface of
that sphere:
deg2km, deg2nm, and deg2sm go from angle in degrees to length
rad2km, rad2nm, and rad2sm go from angle in radians to length
When given a single input argument, all 12 functions assume a radius
of 6,371,000 meters (6371 km, 3440.065 nm, or 3958.748 sm), which is
widely-used as an estimate of the average radius of the Earth. An optional
second parameter can be used to specify a planetary radius (in output length
units) or the name of an object in the Solar System.
Examples of Spherical-Linear Distance Conversions
On the Earth, a degree of arc length at the equator is about 60 nautical miles:
nauticalmiles = deg2nm(1)
nauticalmiles =
60.0405
The Earth is the default assumption for these conversion functions. You can
use other radii, however:
nauticalmiles = deg2nm(1,almanac('moon','radius'))
3-25
Understanding Geospatial Geometry
nauticalmiles =
30.3338
The function deg2sm returns distances in statute, rather than nautical, miles:
deg2sm(1)
ans =
69.0932
Range as an Angle in the distance and reckon Functions
Certain syntaxes of the distance and reckon functions use angles to denote
distances in the way described above. In the following statements, the range
argument, rng, is in degrees (along with all the other inputs and outputs):
[rng, az] = distance(lat1, lon1, lat2, lon2)
[latout, lonout] = reckon(lat, lon, rng, az)
By adding the optional units argument, you can use radians instead:
[rng, az] = distance(lat1, lon1, lat2, lon2, 'radians')
[latout, lonout] = reckon(lat, lon, rng, az, 'radians')
If an ellipsoid argument is provided, however, then rng has units of length,
and they match the units of the semimajor axis length of the reference
ellipsoid. If you specify ellipsoid = [1 0] (the unit sphere) rng can be
considered to either an angle in radians or a length defined in units of earth
radii. It has the same value either way. Thus, in the following computation,
lat1, lon1, lat2, lon2, and az are in degrees, but rng will appear to be in
radians:
[rng, az] = distance(lat1, lon1, lat2, lon2, [1 0])
Summary: Available Distance and Angle Conversion Functions
The following table shows the Mapping Toolbox unit-to-unit distance and arc
conversion functions. They all accept scalar, vector, and higher-dimension
inputs. The first two columns and rows involve angle units, the last three
involve distance units:
3-26
Understanding Angles, Directions, and Distances
Functions that Directly Convert Angles, Lengths, and Spherical Distances
Convert
To Degrees
To Radians
To
Kilometers
To Nautical
Miles
To Statute
Miles
Degrees
toDegrees
fromDegrees
degtorad
toRadians
fromDegrees
deg2km
deg2nm
deg2sm
Radians
radtodeg
toDegrees
fromRadians
toRadians
fromRadians
rad2km
rad2nm
rad2sm
Kilometers
km2deg
km2rad
km2nm
km2sm
Nautical
Miles
nm2deg
nm2rad
nm2km
Statute
Miles
sm2deg
sm2rad
sm2km
nm2sm
sm2nm
The angle conversion functions along the major diagonal, toDegrees,
toRadians, fromDegrees, and fromRadians, can have no-op results. They are
intended for use in applications that have no prior knowledge of what angle
units might be input or desired as output.
Angles as Binary and Formatted Numbers
The terms decimal degrees and decimal minutes are often used in geospatial
data handling and navigation. The preceding section avoided using them
because its focus was on the representation of angles within MATLAB, where
they can be arbitrary binary floating-point numbers.
However, once an angle in degrees is converted to a string, it is often helpful
to describe that string as representing the angle in decimal degrees. Thus,
num2str(radtodeg(1))
ans =
57.2958
gives a value in decimal degrees. In casual communication it is common to
refer to a quantity such as radtodeg(1) as being in decimal degrees, but
strictly speaking, that is not true until it is somehow converted to a string
3-27
Understanding Geospatial Geometry
in base 10. That is, a binary floating-point number is not a decimal number,
whether it represents an angle in degrees or not. If it does represent an angle
and that number is then formatted and displayed as having a fractional part,
only then is it appropriate to speak of decimal degrees. Likewise, the term
decimal minutes applies when you convert a degrees-minutes representation
to a string, as in
num2str(degrees2dm(radtodeg(1)))
ans =
57
17.7468
Formatting Latitudes and Longitudes as Strings
When a DM or DMS representation of an angle is expressed as a string, it
is traditional to tag the different components with the special characters d,
m, and s, or , , and ".
When the angle is a latitude or longitude, a letter often designates the sign
of the angle:
N for positive latitudes
S for negative latitudes
E for positive longitudes
W for negative longitudes
For example, 123 degrees, 30 minutes, 12.7 seconds west of Greenwich can be
written as 123d30m12.7sW, 123 30 12.7" W, or -123 30 12.7".
Use the function str2angle to import latitude and longitude data formatted
as such strings. Conversely, you can format numeric degree data for display
or export with angl2str, or combine degrees2dms or degrees2dm with
sprintf to customize formatting.
See Degrees, Minutes, and Seconds on page 3-20 for more details about
DM and DMS representation.
3-28
Understanding Map Projections
Understanding Map Projections
In this section...
What Is a Map Projection? on page 3-29
Forward and Inverse Projection on page 3-30
Projection Distortions on page 3-30
What Is a Map Projection?
While all geospatial data needs to be georeferenced (pinned to locations on the
Earths surface) in some way, a given data set might or might not explicitly
describe locations with geographic coordinates (latitudes and longitudes).
When it does, many applicationsparticularly map displaycannot make
direct use of geographic coordinates, and must transform them in some way to
plane coordinates. This transformation process, called map projection, is both
algorithmic and the core of the cartographers art.
A map projection is a procedure that unwraps a sphere or ellipsoid to flatten
it onto a plane. Usually this is done through an intermediate surface such
as a cylinder or a cone, which is then unwrapped to lie flat. Consequently,
map projections are classified as cylindrical, conical, and azimuthal (a direct
transformation of the surface of part of a spheroid to a circle). See The
Three Main Families of Map Projections on page 8-5 for discussions and
illustrations of how these transformations work.
Mapping Toolbox map projection libraries feature dozens of map projections,
which you principally control with axesm. Some are ancient and well-known
(such as Mercator), others are ancient and obscure (such as Bonne), while
some are modern inventions (such as Robinson). Some are suitable for
showing the entire world, others for half of it, and some are only useful over
small areas. When geospatial data has geographic coordinates, any projection
can be applied, although some are not good choices. The toolbox can project
both vector data and raster data.
See Chapter 8, Using Map Projections and Coordinate Systems for more
details on the properties of different classes of projections. For a list of
Mapping Toolbox map projections, with links to their reference pages,
see Chapter 14, Map Projections Reference. Summary and Guide to
3-29
Understanding Geospatial Geometry
Projections on page 8-63 lists all the available map projections and their
intrinsic properties.
Forward and Inverse Projection
When geospatial data has plane coordinates (i.e., it comes preprojected, as
do many satellite images and municipal map data sets), it is usually possible
to recover geographic coordinates if the projection parameters and datum
are known. Using this information, you can perform an inverse projection,
running the projection backward to solve for latitude and longitude. The
toolbox can perform accurate inverse projections for any of its projection
functions as long as the original projection parameters and reference ellipsoid
(or spherical radius) are provided to it.
Note Converting a position given in latitude-longitude to its equivalent in
a projected map coordinate system involves converting from units of angle
to units of length. Likewise, unprojecting a point position changes its units
from those of length to those of angle). Unit conversion functions such as
deg2km and km2deg also convert coordinates between angles and lengths,
but do not transform the space they inhabit. You cannot use them to project
or unproject coordinate data.
Projection Distortions
All map projections introduce distortions compared to maps on globes.
Distortions are inherent in flattening the sphere, and can take several forms:
Areas Relative size of objects (such as continents)
Distances Relative separations of points (such as a set of cities)
Directions Azimuths (angles between points and the poles)
Shapes Relative lengths and angles of intersection
Some classes of map projections maintain areas, and others preserve local
shapes, distances, and/or directions. No projection, however, can preserve
all these characteristics. Choosing a projection thus always requires
compromising accuracy in some way, and that is one reason why so many
different map projections have been developed. For any given projection,
3-30
Understanding Map Projections
however, the smaller the area being mapped, the less distortion it introduces
if properly centered. Mapping Toolbox tools help you to quantify and visualize
projection distortions.
3-31
Understanding Geospatial Geometry
Great Circles, Rhumb Lines, and Small Circles
In this section...
Great Circles on page 3-32
Rhumb Lines on page 3-32
Small Circles on page 3-33
Great Circles
In plane geometry, lines have two important characteristics. A line represents
the shortest path between two points, and the slope of such a line is constant.
When describing lines on the surface of a spheroid, however, only one of these
characteristics can be guaranteed at a time.
A great circle is the shortest path between two points along the surface of
a sphere. The precise definition of a great circle is the intersection of the
surface with a plane passing through the center of the planet. Thus, great
circles always bisect the sphere. The equator and all meridians are great
circles. All great circles other than these do not have a constant azimuth, the
spherical analog of slope; they cross successive meridians at different angles.
That great circles are the shortest path between points is not always apparent
from maps, because very few map projections (the Gnomonic is one of them)
represent arbitrary great circles as straight lines.
Because they define paths that minimize distance between two (or three)
points, great circles are examples of geodesics. In general, a geodesic is the
straightest possible path constrained to lie on a curved surface, independent
of the choice of a coordinate system. The term comes from the Greek geo-,
earth, plus daiesthai, to divide, which is also the root word of geodesy, the
science of describing the size and shape of the Earth mathematically.
Rhumb Lines
A rhumb line is a curve that crosses each meridian at the same angle. This
curve is also referred to as a loxodrome (from the Greek loxos, slanted, and
drome, path). Although a great circle is a shortest path, it is difficult to
navigate because your bearing (or azimuth) continuously changes as you
3-32
Great Circles, Rhumb Lines, and Small Circles
proceed. Following a rhumb line covers more distance than following a
geodesic, but it is easier to navigate.
All parallels, including the equator, are rhumb lines, since they cross all
meridians at 90. Additionally, all meridians are rhumb lines, in addition to
being great circles. A rhumb line always spirals toward one of the poles,
unless its azimuth is true east, west, north, or south, in which case the rhumb
line closes on itself to form a parallel of latitude (small circle) or a pair of
antipodal meridians.
The following figure depicts a great circle and one possible rhumb line
connecting two distant locations. Descriptions and examples of how to
calculate points along great circles and rhumb lines appear below.
Great Circle
(shortest distance)
Rhumb Line
(constant azimuth)
Small Circles
In addition to rhumb lines and great circles, one other smooth curve is
significant in geography, the small circle. Parallels of latitude are all small
circles (which also happen to be rhumb lines). The general definition of
a small circle is the intersection of a plane with the surface of a sphere.
On ellipsoids, this only yields true small circles when the defining plane is
parallel to the equator. Mapping Toolbox software extends this definition to
3-33
Understanding Geospatial Geometry
include planes passing through the center of the planet, so the set of all small
circles includes all great circles as limiting cases. This usage is not universal.
Small circles are most easily defined by distance from a point. All points 45
nm (nautical miles) distant from (45N,60E) would be the description of one
small circle. If degrees of arc length are used as a distance measurement,
then (on a sphere) a great circle is the set of all points 90 distant from a
particular center point.
For true small circles, the distance must be defined in a great circle sense, the
shortest distance between two points on the surface of a sphere. However,
Mapping Toolbox functions also can calculate loxodromic small circles, for
which distances are measured in a rhumb line sense (along lines of constant
azimuth). Do not confuse such figures with true small circles.
Computing Small Circles
You can calculate vector data for points along a small circle in two ways. If
you have a center point and a known radius, use scircle1; if you have a
center point and a single point along the circumference of the small circle, use
scircle2. For example, to get data points describing the small circle at 10
distance from (67N, 135W), use the following:
[latc,lonc] = scircle1(67,-135,10);
To get the small circle centered at the same point that passes through the
point (55N,135W), use scircle2:
[latc,lonc] = scircle2(67,-135,55,-135);
3-34
Great Circles, Rhumb Lines, and Small Circles
scircle1
scircle2
Perimeter
point
Radius
Center point
Center point
Output points
The scircle1 function also allows you to calculate points along a specific
arc of the small circle. For example, if you want to know the points 10 in
distance and between 30 and 120 in azimuth from (67N,135W), simply
provide arc limits:
[latc,lonc] = scircle1(67,-154,10,[30 120]);
scircle1 with arc limits
Points outside
arc limits are
not returned.
Center
point
Azimuth1 = 30o
Points within
arc limits
are returned.
Radius
Azimuth2 = 120o
When an entire small circle is calculated, the data is in polygon format. For
all calculated small circles, 100 points are returned unless otherwise specified.
You can calculate several small circles at once by providing vector inputs. For
more information, see the scircle1 and scircle2 function reference pages.
3-35
Understanding Geospatial Geometry
An Annotated Map Illustrating Small Circles. The following Mapping
Toolbox commands illustrate generating small circles of the types described
above, including the limiting case of a large circle. To execute these
commands, select them all by dragging over the list in the Help browser, then
click the right mouse button and choose Evaluate Selection:
figure;
axesm ortho; gridm on; framem on
setm(gca,'Origin', [45 30 30], 'MLineLimit', [75 -75],...
'MLineException',[0 90 180 270])
A = [45 90];
B = [0 60];
C = [0 30];
sca = scircle1(A(1), A(2), 20);
scb = scircle2(B(1), B(2), 0, 150);
scc = scircle1('rh',C(1), C(2), 20);
plotm(A(1), A(2),'ro','MarkerFaceColor','r')
plotm(B(1), B(2),'bo','MarkerFaceColor','b')
plotm(C(1), C(2),'mo','MarkerFaceColor','m')
plotm(sca(:,1), sca(:,2),'r')
plotm(scb(:,1), scb(:,2),'b--')
plotm(scc(:,1), scc(:,2),'m')
textm(50,0,'Normal Small Circle')
textm(46,6,'(20\circ from point A)')
textm(4.5,-10,'Loxodromic Small Circle')
textm(4,-6,'(20\circ from point C')
textm(-2,-4,'in rhumb line sense)')
textm(40,-60,'Great Circle as Small Circle')
textm(45,-50,'(90\circ from point B)')
The result is the following display.
3-36
Great Circles, Rhumb Lines, and Small Circles
3-37
Understanding Geospatial Geometry
Directions and Areas on the Sphere and Spheroid
In this section...
About Azimuths on page 3-38
Reckoning The Forward Problem on page 3-38
Distance, Azimuth, and Back-Azimuth (the Inverse Problem) on page 3-41
Measuring Area of Spherical Quadrangles on page 3-44
About Azimuths
Azimuth is the angle a line makes with a meridian, measured clockwise from
north. Thus the azimuth of due north is 0, due east is 90, due south is 180,
and due west is 270. You can instruct several Mapping Toolbox functions to
compute azimuths for any pair of point locations, either along rhumb lines
or along great circles. These will have different results except along cardinal
directions. For great circles, the result is the azimuth at the initial point of
the pair defining a great circle path. This is because great circle azimuths
other than 0, 90, 180, and 270 do not remain constant. Azimuths for rhumb
lines are constant along their entire path (by definition).
For rhumb lines, computing an azimuth backward (from the second point to
the first) yields the complement of the forward azimuth ((Az + 180) mod
360). For great circles, the back azimuth is generally not the complement,
and the difference depends on the distance between the two points.
In addition to forward and back azimuths, Mapping Toolbox functions can
compute locations of points a given distance and azimuth from a reference
point, and can calculate tracks to connect waypoints, along either great circles
or rhumb lines on a sphere or ellipsoid.
Reckoning The Forward Problem
A common problem in geographic applications is the determination of a
destination given a starting point, an initial azimuth, and a distance. In the
toolbox, this process is called reckoning. A new position can be reckoned in a
great circle or a rhumb line sense (great circle or rhumb line track).
3-38
Directions and Areas on the Sphere and Spheroid
As an example, an airplane takes off from La Guardia Airport in New York
(40.75N, 73.9W) and follows a northwestern rhumb line flight path at 200
knots (nautical miles per hour). Where would it be after 1 hour?
[rhlat,rhlong] = reckon('rh',40.75,-73.9,nm2deg(200),315)
rhlat =
43.1054
rhlong =
-77.0665
Notice that the distance, 200 nautical miles, must be converted to degrees of
arc length with the nm2deg conversion function to match the latitude and
longitude inputs. If the airplane had a flight computer that allowed it to
follow an exact great circle path, what would the aircrafts new location be?
[gclat,gclong] = reckon('gc',40.75,-73.9,nm2deg(200),315)
gclat =
43.0615
gclong =
-77.1238
Notice also that for short distances at these latitudes, the result hardly differs
between great circle and rhumb line. The two destination points are less than
4 nautical miles apart. Incidentally, after 1 hour, the airplane would be just
north of New Yorks Finger Lakes.
Calculating Tracks Great Circles and Rhumb Lines
You can generate vector data corresponding to points along great circle or
rhumb line tracks using track1 and track2. If you have a point on the track
and an azimuth at that point, use track1. If you have two points on the track,
use track2. For example, to get the great circle path starting at (31S, 90E)
with an azimuth of 45 with a length of 12, use track1:
[latgc,longc] = track1('gc',-31,90,45,12);
For the great circle from (31S, 90E) to (23S, 110E), use track2:
[latgc,longc] = track2('gc',-31,90,-23,110);
3-39
Understanding Geospatial Geometry
track1
track2
Output points
Final point
Initial point
Azimuth and range
Initial point
Output points
The track1 function also allows you to specify range endpoints. For example,
if you want points along a rhumb line starting 5 away from the initial point
and ending 13 away, at an azimuth of 55, simply specify the range limits:
[latrh,lonrh] = track1('rh',-31,90,55,[5 13]);
track1 with range limits
s
oint
tp
utpu
Azimuth
Initial
point
Range1
Range2
When no range is provided for track1, the returned points represent a
complete track. For great circles, a complete track is 360, encircling the
planet and returning to the initial point. For rhumb lines, the complete track
terminates at the poles, unless the azimuth is 90 or 270, in which case the
complete track is a parallel that returns to the initial point.
For calculated tracks, 100 points are returned unless otherwise specified. You
can calculate several tracks at one time by providing vector inputs. For more
3-40
Directions and Areas on the Sphere and Spheroid
information, see the track1 and track2 reference pages. More vector path
calculations are described later in Navigation on page 10-11.
Distance, Azimuth, and Back-Azimuth (the Inverse
Problem)
When Mapping Toolbox functions calculate the distance between two points
in geographic space, the result depends upon whether you specify great circle
or rhumb line distance. The distance function returns the appropriate
distance between two points as an angular arc length, employing the same
angular units as the input latitudes and longitudes. The default path type
is the shorter great circle, and the default angular units are degrees. The
previous figure shows two points at (15S, 0) and (60N, 150E). The great
circle distance between them, in degrees of arc, is as follows:
distgc = distance(-15,0,60,150)
distgc =
129.9712
The rhumb line distance is greater:
distrh = distance('rh',-15,0,60,150)
distrh =
145.0288
To determine how much longer the rhumb line path is in, say, kilometers, you
can use a distance conversion function on the difference:
kmdifference = deg2km(distrh-distgc)
kmdifference =
1.6744e+03
Several distance conversion functions are available in the toolbox, supporting
degrees, radians, kilometers, meters, statute miles, nautical miles, and feet.
Converting distances between angular arc length units and surface length
units requires the radius of a planet or spheroid. By default, the radius
of the Earth is used.
3-41
Understanding Geospatial Geometry
Calculating Azimuth and Elevation
Azimuth is the angle a line makes with a meridian, taken clockwise from
north. When the azimuth is calculated from one point to another using the
toolbox, the result depends upon whether you want a great circle or a rhumb
line azimuth. For great circles, the result is the azimuth at the starting point
of the connecting great circle path. In general, the azimuth along a great
circle is not constant. For rhumb lines, the resulting azimuth is constant
along the entire path.
Azimuths, or bearings, are returned in the same angular units as the input
latitudes and longitudes. The default path type is the shorter great circle,
and the default angular units are degrees. In the example, the great circle
azimuth from the first point to the second is
azgc = azimuth(-15,0,60,150)
azgc =
19.0391
For the rhumb line, the constant azimuth is
azrh = azimuth('rh',-15,0,60,150)
azrh =
58.8595
One feature of rhumb lines is that the inverse azimuth, from the second point
to the first, is the complement of the forward azimuth and can be calculated
by simply adding 180 to the forward value:
inverserh = azimuth('rh',60,150,-15,0)
inverserh =
238.8595
difference = inverserh-azrh
difference =
180
This is not true, in general, of great circles:
3-42
Directions and Areas on the Sphere and Spheroid
inversegc = azimuth('gc',60,150,-15,0)
inversegc =
320.9353
difference = inversegc-azgc
difference =
301.8962
The azimuths associated with cardinal and intercardinal compass directions
are the following:
North
0 or 360
Northeast
45
East
90
Southeast
135
South
180
Southwest
225
West
270
Northwest
315
Elevation is the angle above the local horizontal of one point relative to the
other. To compute the elevation angle of a second point as viewed from the
first, provide the position and altitude of the points. The default units are
degrees for latitudes and longitudes and meters for altitudes, but you can
specify other units for each. What are the elevation, slant range, and azimuth
of a point 10 kilometers east and 10 kilometers above a surface point?
[elevang,slantrange,azim] = elevation(0,0,0,0,km2deg(10),10000)
elevang =
44.901
slantrange =
14156
azim =
3-43
Understanding Geospatial Geometry
90
On an ellipsoid, azimuths returned from elevation generally will differ from
those returned by azimuth and distance.
Measuring Area of Spherical Quadrangles
In solid geometry, the area of a spherical quadrangle can be exactly calculated.
A spherical quadrangle is the intersection of a lune and a zone. In geographic
terms, a quadrangle is defined as a region bounded by parallels north and
south, and meridians east and west.
Quadrangle
Zone
Lune
In the pictured example, a quadrangle is formed by the intersection of a zone,
which is the region bounded by 15N and 45N latitudes, and a lune, which
is the region bounded by 0 and 30E longitude. Under the spherical planet
assumption, the fraction of the entire spherical surface area inscribed in the
quadrangle can be calculated:
area = areaquad(15,0,45,30)
area =
0.0187
3-44
Directions and Areas on the Sphere and Spheroid
That is, less than 2% of the planets surface area is in this quadrangle. To
get an absolute figure in, for example, square miles, you must provide the
appropriate spherical radius. The radius of the Earth is about 3958.9 miles:
area = areaquad(15,0,45,30,3958.9)
area =
3.6788e+06
The surface area within this quadrangle is over 3.6 million square miles for a
spherical Earth.
3-45
Understanding Geospatial Geometry
Planetary Almanac Data
Mapping Toolbox functions include one that provides almanac data (size and
shape statistics) for the major bodies of our solar system. Basic geometric
parameters, such as ellipsoid vectors, radii, surface areas, and volumes, can
be accessed for the Sun, the Earths moon, and all of the planets, in any of the
supported units of distance measurement.
Many planets have ellipsoid vectors available. Some planets return spherical
ellipsoid vectors only:
almanac('earth','ellipsoid','nauticalmiles')
ans =
3443.92
0.08
almanac('mars','ellipsoid','kilometers')
ans =
3396.90
0.11
almanac('moon','ellipsoid','statutemiles')
ans =
1079.97
When you specify 'radius', a scalar is returned representing the radius of
the best spherical model of the planet. Notice that for a spherical model, the
radius in radians is 1:
almanac('mercury','radius','kilometers')
ans =
2439
almanac('neptune','radius','radians')
ans =
1
3-46
Planetary Almanac Data
Surface areas and volumes are calculated based on a spherical model by
default. In most cases, you can use the ellipsoid model instead, and for the
Earth you can specify any of the supported ellipsoid models. You can also
request the actual tabulated values of the Earth:
almanac('mars','surfarea','kilometers','ellipsoid')
ans =
1.4441e+08
almanac('earth','volume','kilometers','international')
ans =
1.0833e+12
almanac('earth','volume','kilometers','actual')
ans =
1.0832e+12
For a complete description of available data, see the almanac reference page.
3-47
3-48
Understanding Geospatial Geometry
4
Creating and Viewing Maps
Introduction to Mapping Graphics on page 4-2
Using worldmap and usamap on page 4-4
Axes for Drawing Maps on page 4-12
Controlling Map Frames and Grids on page 4-46
Displaying Vector Data with Mapping Toolbox Functions on page 4-58
Displaying Data Grids on page 4-68
Interacting with Displayed Maps on page 4-76
Creating and Viewing Maps
Introduction to Mapping Graphics
Even though geospatial data often is manipulated and analyzed without being
displayed, high-quality interactive cartographic displays can play valuable
roles in exploratory data analysis, application development, and presentation
of results.
Using Mapping Toolbox capabilties, you can display geographic information
almost as easily as you can display tabular or time-series data in MATLAB
plots. Most mapping functions are similar to MATLAB plotting functions,
except they accept data with geographic/geodetic coordinates (latitudes and
longitudes) instead of Cartesian and polar coordinates. Mapping functions
typically have the same names as their MATLAB counterparts, with the
addition of an 'm' suffix (for maps). For example, the Mapping Toolbox analog
to the MATLAB plot function is plotm.
Mapping Toolbox software manages most of the details in displaying a map.
It projects your data, cuts and trims it to specified limits, and displays the
resulting map at various scales. With the toolbox you can also add customary
cartographic elements, such as a frame, grid lines, coordinate labels, and
text labels, to your displayed map. If you change your projection properties,
or even the projection itself, some Mapping Toolbox map displays are
automatically redrawn with the new settings, undoing any cuts or trims if
necessary. See Accessing, Computing, and Inverting Map Projection Data
on page 8-37 for information on how to project data without displaying it.
The toolbox also makes it easy to modify and manipulate maps. You can
modify the map display and mapped objects either from the command line or
through and property editing tools you can invoke by clicking on the display.
4-2
Introduction to Mapping Graphics
Note In its current implementation, the toolbox maintains the map projection
and display properties by storing special data in the UserData property of
the map axes. The toolbox also takes over the UserData property of mapped
objects. Therefore, never attempt to set the UserData property of a map axes
or a projected map object. Do not apply the MATLAB get function to axes
UserData, depend on the contents of UserData in any way, or apply functions
that set or get UserData to the handles of map axes or mapped objects. Only
use the Mapping Toolbox functions getm and setm to obtain and modify map
axes properties.
4-3
Creating and Viewing Maps
Using worldmap and usamap
In this section...
Continent, Country, Region, and State Maps Made Easy on page 4-4
Using worldmap on page 4-5
Using usamap on page 4-7
Continent, Country, Region, and State Maps Made
Easy
Mapping Toolbox functions axesm and setm enable you to control the full range
of properties when constructing a projected map axes. Functions worldmap
and usamap, on the other hand, trade control for simplicity and convenience.
These two functions each create a map axes object that is suitable for a
country or region of the world or the United States, automatically selecting
the map projection, limits, and other properties based on the name of the area
you want to map. Once you have jump-started your map with worldmap or
usamap, you are ready to add your data, using geoshow or any of the lower
level geographic data display functions. Optionally, you can use the map axes
object created by worldmap or usamap as a starting point, and then customize
it by adjusting selected properties with setm.
Setting Background Colors for Map Displays
The default color for MATLAB figures is gray. If you prefer that your maps
have white backgrounds instead, you can create figures with the command
figure('Color','white')
If you want a custom background color, specify a color triplet in place of
white. For example, to make a beige background, type
figure('Color',[.95 .9 .8])
To give a white background to an existing figure, type
set(gca,'color','white')
4-4
Using worldmap and usamap
If you want all figures in a session to have white backgrounds, set this as a
default with the command
set(0, 'DefaultFigureColor', 'white');
To avoid having to do this every time you start MATLAB, place this command
in your startup.m file.
You can also use the Property Editor, part of the MATLAB plotting tools,
to modify background colors for figures and axes. See Plotting Tools
Interactive Plotting in the MATLAB Graphics documentation for more
information.
Using worldmap
Here are two examples that create simple maps using sample data sets from
matlabroot/toolbox/map/mapdemos. The first one creates a map of South
America with land areas, major lakes and rivers, and populated places.
1 First, set up the map frame, allowing worldmap to pick a projection:
figure
worldmap 'south america'
axis off
4-5
Creating and Viewing Maps
80 W
60 W
40 W
20 S
40 S
60 S
2 You can find out what map projection worldmap selected this way:
getm(gca,'MapProjection')
ans =
eqdconic
This denotes the Equidistant Conic Projection, which is appropriate for
regions in middle latitudes that are elongated along the polar axis.
3 Next, use geoshow to import data for land areas, major rivers, and major
cities from shapefiles and display it using colors you specify:
4-6
Using worldmap and usamap
geoshow('landareas.shp', 'FaceColor', [0.5 0.7 0.5])
geoshow('worldrivers.shp', 'Color', 'blue')
geoshow('worldcities.shp', 'Marker', '.', 'Color', 'red')
The map now looks like this.
Using usamap
The usamap function allows you to make maps of the United States as a whole,
just the conterminous portion (the lower 48 states), groups of states or a
single state. The easiest way to use it is to type
usamap
4-7
Creating and Viewing Maps
at the MATLAB prompt. This opens a GUI with a list box from which you can
select the entire U.S., the conterminous states, or an individual state to map.
The map axes you create with usamap has a labelled grid fitted around the
area you specify, but contains no data, allowing you to generate the kind of
map you want using display functions such as geoshow.
This example creates a map of the Chesapeake Bay region by specifying
geographic limits.
1 First, specify limits and set up a map axes object:
latlim = [ 37 40];
lonlim = [-78 -74];
figure
ax = usamap(latlim,lonlim);
axis off
4-8
Using worldmap and usamap
40 N
39 N
38 N
37 N
78 W
77 W
76 W
75 W
74 W
The Lambert Conformal Conic Projection is often used for maps of the
conterminous United States.
2 Here is the map projection usamap selected:
getm(gca,'MapProjection')
ans =
lambert
3 Next, use shaperead to read U.S. state polygon boundaries from the
usastatehi demo shapefile into a geostruct named states:
states = shaperead('usastatehi',...
'UseGeoCoords', true, 'BoundingBox', [lonlim', latlim']);
4-9
Creating and Viewing Maps
4 Make a symbolspec to create a political map using the polcmap function:
faceColors = makesymbolspec('Polygon',...
{'INDEX', [1 numel(states)], ...
'FaceColor', polcmap(numel(states))});
5 Display the filled polygons with geoshow:
geoshow(ax, states, 'SymbolSpec', faceColors)
6 Extract the names for states within the window from the geostruct and use
textm to plot them at the label points provided by the geostruct:
for k = 1:numel(states)
labelPointIsWithinLimits =...
latlim(1) < states(k).LabelLat &&...
latlim(2) > states(k).LabelLat &&...
lonlim(1) < states(k).LabelLon &&...
lonlim(2) > states(k).LabelLon;
if labelPointIsWithinLimits
textm(states(k).LabelLat,...
states(k).LabelLon, states(k).Name, ...
'HorizontalAlignment', 'center')
end
end
textm(38.2,-76.1,' Chesapeake Bay ',...
'fontweight','bold','Rotation', 270)
4-10
Using worldmap and usamap
40 N
39 N
Maryland
District of Columbia
Chesapeake Bay
38 N
37 N
78 W
Delaware
77 W
76 W
75 W
74 W
Note that as polcmap assigns random pastel colors to patches, your map
might display different colors than this example. For further information on
options for these functions, see the reference pages for geoshow, shaperead,
worldmap, and usamap.
4-11
Creating and Viewing Maps
Axes for Drawing Maps
In this section...
What Is a Map Axes? on page 4-12
Using axesm on page 4-13
Accessing and Manipulating Map Axes Properties on page 4-14
Using the Map Limit Properties on page 4-19
Switching Between Projections on page 4-34
Projected and Unprojected Graphic Objects on page 4-37
What Is a Map Axes?
When you create a map, you can use one of the Mapping Toolbox built-in user
interfaces (UIs), or you can build the graphic with MATLAB and Mapping
Toolbox functions. Many MATLAB graphics are built using the axes function:
axes
axes('PropertyName',PropertyValue,...)
axes(h)
h = axes(...)
Mapping Toolbox functions include an extended version of axes, called
axesm, that includes information about the current coordinate system (map
projection), as well as data to define the map grid and its labeling, the map
frame and its limits, and other properties. Its syntax is similar to that of axes:
axesm
axesm(PropertyName,PropertyValue,...)
axesm(ProjectionFcn,PropertyName,PropertyValue,...)
The axesm function without arguments brings up a UI that lists all supported
projections and assists in defining their parameters. You can also summon
this UI with the axesmui function once you have created a map axes.
You can also list all the names, classes, and ID strings of Mapping Toolbox
map projections with the maps function.
4-12
Axes for Drawing Maps
Axes created with axesm share all properties associated with regular axes,
and have additional properties related to projections, scale, and positioning
in geographic coordinates. See the axes and axesm reference pages for lists
of properties.
You can place many types of objects in a map axes, such as lines, patches,
markers, scale rulers, north arrows, grids, and text. You can use the handlem
function and its associated UI to list these objects and obtain handles to them.
See the handlem reference page for a list of the objects that can occupy a
map axes and how to query for them.
Map axes objects created by axesm contain projection information in a
structure. For an example of what these properties are, type
h = axesm('MapProjection','mercator')
and then use the getm function to retrieve all the map axes properties:
p = getm(h)
For complete descriptions of all map axes properties, see the axesm reference
page. For more information on the use of axesmui, refer to the axesm,
axesmui reference page.
Using axesm
The figure window created using axesm contains the same set of tools and
menus as any MATLAB figure, and is by default blank, even if there is map
data in your workspace. You can toggle certain properties, such as grids,
frames, and axis labels, by right-clicking in the figure window to obtain
a pop-up menu.
You can define multiple independent figures containing map axes, but only
one can be active at any one time. Return handles for them when you create
them to allow them to be referenced when they are no longer current. Use
axes(handle) to activate an existing map axes object.
4-13
Creating and Viewing Maps
Accessing and Manipulating Map Axes Properties
Just as the properties of the underlying standard axes can be accessed and
manipulated using the MATLAB functions set and get, map axes properties
can also be accessed and manipulated using the functions setm and getm.
Note Use the axesm function only to create a map axes object. Use the setm
function to modify existing map axes.
1 As an example, create a map axes object containing no map data:
axesm('MapProjection','miller','Frame','on')
Note that you specify MapProjection string values in lowercase. At this
point you can begin to customize the map. For example, you might decide
to make the frame lines bordering the map thicker. First, you need to
identify the current line width of the frame, which you do by querying
the current axes, identified as gca.
2 Access the current FLineWidth property value by typing
getm(gca,'FLineWidth')
ans =
2
3 Now reset the line width to four points. The default fontunits value for
axes is points. You can set fontunits to be points, normalized, inches,
centimeters, or pixels.
setm(gca,'FLineWidth',4)
4 You can set any number of properties simultaneously with setm. Continue
by reducing the line width, changing the projection to equidistant
cylindrical, and verify the changes:
setm(gca,'FLineWidth',3,'MapProjection','eqdcylin')
getm(gca,'FLineWidth')
ans =
3
4-14
Axes for Drawing Maps
getm(gca,'MapProjection')
ans =
eqdcylin
5 To inspect the entire set of map axes properties at their current settings,
use the following command:
getm(gca)
ans =
mapprojection:
zone:
angleunits:
aspect:
falseeasting:
falsenorthing:
fixedorient:
geoid:
maplatlimit:
maplonlimit:
mapparallels:
nparallels:
origin:
scalefactor:
trimlat:
trimlon:
frame:
ffill:
fedgecolor:
ffacecolor:
flatlimit:
flinewidth:
flonlimit:
grid:
galtitude:
gcolor:
glinestyle:
glinewidth:
mlineexception:
mlinefill:
mlinelimit:
'eqdcylin'
[]
'degrees'
'normal'
[]
[]
[]
[1 0]
[-90 90]
[-180 180]
30
1
[0 0 0]
[]
[-90 90]
[-180 180]
'on'
100
[0 0 0]
'none'
[-90 90]
3
[-180 180]
'off'
Inf
[0 0 0]
':'
0.5000
[]
100
[]
4-15
Creating and Viewing Maps
mlinelocation:
mlinevisible:
plineexception:
plinefill:
plinelimit:
plinelocation:
plinevisible:
fontangle:
fontcolor:
fontname:
fontsize:
fontunits:
fontweight:
labelformat:
labelunits:
meridianlabel:
mlabellocation:
mlabelparallel:
mlabelround:
parallellabel:
plabellocation:
plabelmeridian:
plabelround:
30
'on'
[]
100
[]
15
'on'
'normal'
[0 0 0]
'helvetica'
9
'points'
'normal'
'compass'
'degrees'
'off'
30
90
0
'off'
15
-180
0
Note that the list of properties includes both those particular to map axes
and general ones that apply to all MATLAB axes.
6 Similarly, use the setm function alone to display the set of properties, their
enumerated values, and defaults:
setm(gca)
AngleUnits
Aspect
FalseEasting
FalseNorthing
FixedOrient
Geoid
MapLatLimit
MapLonLimit
MapParallels
4-16
[ {degrees} | radians ]
[ {normal} | transverse ]
FixedOrient is a read-only property
Axes for Drawing Maps
MapProjection
NParallels
Origin
ScaleFactor
TrimLat
TrimLon
Zone
Frame
FEdgeColor
FFaceColor
FFill
FLatLimit
FLineWidth
FLonLimit
Grid
GAltitude
GColor
GLineStyle
GLineWidth
MLineException
MLineFill
MLineLimit
MLineLocation
MLineVisible
PLineException
PLineFill
PLineLimit
PLineLocation
PLineVisible
FontAngle
FontColor
FontName
FontSize
FontUnits
{points} | pixels ]
FontWeight
LabelFormat
LabelRotation
LabelUnits
MeridianLabel
NParallels is a read-only property
TrimLat is a read-only property
TrimLon is a read-only property
[ on | {off} ]
[ on | {off} ]
[ - | -- | -. | {:} ]
[ {on} | off ]
[ {on} | off ]
[ {normal} | italic | oblique ]
[ inches | centimeters | normalized |
[
[
[
[
[
{normal} | bold ]
{compass} | signed | none ]
on | {off} ]
{degrees} | radians ]
on | {off} ]
4-17
Creating and Viewing Maps
MLabelLocation
MLabelParallel
MLabelRound
ParallelLabel
PLabelLocation
PLabelMeridian
PLabelRound
[ on | {off} ]
Many, but not all, property choices and defaults can also be displayed
individually:
setm(gca,'AngleUnits')
AngleUnits
[ {degrees} | radians ]
setm(gca,'MapProjection')
An axes's "MapProjection" property does not have a fixed set
of property values.
setm(gca,'Frame')
Frame
[ on | {off} ]
setm(gca,'FixedOrient')
FixedOrient
FixedOrient is a read-only property
7 In the same way, getm displays the current value of any axes property:
getm(gca,'AngleUnits')
ans =
degrees
getm(gca,'MapProjection')
ans =
eqdconic
getm(gca,'Frame')
ans =
on
getm(gca,'FixedOrient')
ans =
[]
4-18
Axes for Drawing Maps
For a complete listing and descriptions of map axes properties, see the
reference page for axesm. To identify what properties apply to a given map
projection, see the reference page for that projection.
Using the Map Limit Properties
In many common situations, the map limit properties, MapLatLimit and
MapLonLimit, provide a convenient way of specifying your map projection
origin or frame limits. Note that these properties are intentionally redundant;
you can always avoid them if you wish and instead use the Origin,
FLatLimit, and FLonLimit properties to set up your map. When theyre
applicable, however, youll probably find that its easier and more intuitive
to set MapLatLimit and MapLonLimit, especially when creating a new map
axes with axesm.
Example 1: Robinson Projection
Often, youll want to create a map using a cylindrical projection (such as
Mercator, Miller, or Plate Care) or a pseudo-cylindrical projection (such as
Mollweide or Robinson) showing all or most of the Earth, with the Equator
running as a straight horizontal line across the center of the map. Your map
will be bounded by a geographic quadrangle, and the projection origin will
be located on the Equator and centered between the longitude limits. In this
case, you can easily control the north-south extent of the quadrangle with
the MapLatLimit property and the east-west extent with the MapLonLimit
property. axesm will automatically set the Origin and assign consistent
values for the frame limits (FLatLimit and FLonLimit).
For example, heres a way to create a map with a Robinson projection showing
the western Pacific Ocean and surrounding areas:
latlim = [-80 80];
lonlim = [100 -120];
figure('Color','white')
axesm('robinson','MapLatLimit',latlim,'MapLonLimit',lonlim, ...
'Frame','on','Grid','on','MeridianLabel','on', ...
'ParallelLabel','on')
axis off
setm(gca,'MLabelLocation',60)
coast = load('coast.mat');
4-19
Creating and Viewing Maps
plotm(coast.lat,coast.long)
Note The western limit (100 degrees E, in this case) must always precede the
eastern limit (-120 degrees E, or 120 degrees W), even if the second number in
the longitude-limit vector is smaller than the first.
Note that the map spans 140 degrees from west to east:
wrapTo360(diff(lonlim))
ans =
140
axesm automatically sets the Origin and frame limits based on the values
you selected for MapLatLim and MapLonLim. You can check the Origin and
frame limits by using getm.
origin = getm(gca,'Origin');
flatlim = getm(gca,'FLatLimit');
flonlim = getm(gca,'FLonLimit');
4-20
Axes for Drawing Maps
The origin longitude should be located halfway between the longitude limits of
100 E and 120 W. Adding half of 140 to the western limit gives 100 + 70 = 170
degrees E. This should, and does, equal the second element of the origin vector:
origin(2)
ans =
170
The frame is centered on this longitude with a half-width of 70 degrees:
flonlim
flonlim =
-70
70
The story with latitudes is somewhat simpler; the origin latitude is on the
Equator:
origin(1)
ans =
0
and therefore the latitude limits of the frame equal the value supplied for
MapLatLimit:
flatlim
flatlim =
-80
80
Of course, after youve called axesm, you may look at your map and decide that
youre not completely satisfied with your initial choice of map limits. Suppose
that you decide it would be better to shift the western longitude limit to 40
degrees E in order to include a little more of Asia. You can do this by calling
setm with a new MapLonLimit value:
setm(gca,'MapLonLimit',[40 -120])
but the asymmetric appearance of the resulting map may surprise you.
4-21
Creating and Viewing Maps
You might have expected to see a symmetric map just like the one you would
get if you replaced lonlim in the earlier call to axesm with [40 -120], but
thats not what happened. This apparent inconsistency turns out to be an
important consequence of the fact that MapLatLimit and MapLonLimit are
redundant properties.
Before you call axesm, none of the map axes properties have been set yet
because the map axes doesnt exist. Therefore, theres no value yet for the
Origin property, and theres no problem in setting the longitude origin
halfway between the longitudes specified in the MapLonLimit vector. But once
axesm has been called, your map axes does have a projection origin. Since the
projection origin is such a fundamental property, it takes precedence over
the MapLonLimit property.
Therefore, if you try to reset your longitude limits without also resetting the
origin, setm will maintain your current origin. So, the center of the map
limits moved west, but the origin stayed fixed. This combination caused the
asymmetry.
4-22
Axes for Drawing Maps
To avoid this asymmetry, you can repeat the operations shown above to figure
out that the new central longitude must be at 140 degrees E and add this
in the call to setm like this:
setm(gca,'MapLonLimit',[40 -120],'Origin',[0 140])
but you dont actually need to go through such trouble.
Instead, you can just tell setm that youd like to calculate a new origin by
providing an empty array instead of a new value for the Origin property.
setm(gca,'MapLonLimit',[40 -120],'Origin',[])
Notice the symmetry of the resulting map frame. Usually this is the easiest
thing to do.
Example 2: Cylindrical Projection
Load the coast MAT-file.
coast = load('coast');
4-23
Creating and Viewing Maps
Construct a Mercator projection covering the full range of permissible
latitudes with longitudes covering a full 360 degrees starting at 60 West.
figure('Color','w')
axesm('mercator','MapLatLimit',[-90 90],'MapLonLimit',[-60 300])
axis off; framem on; gridm on; mlabel on; plabel on;
setm(gca,'MLabelLocation',60)
geoshow(coast.lat,coast.long,'DisplayType','polygon')
The call to axesm above is equivalent to:
axesm('mercator','Origin',[0 120 0], ...
'FLatLimit',[-90 90],'FlonLimit',[-180 180])
You can verify this by checking these properties:
getm(gca,'Origin')
getm(gca,'FLatLimit')
getm(gca,'FLonLimit')
ans =
0
ans =
4-24
120.00
Axes for Drawing Maps
-86.00
86.00
-180.00
180.00
ans =
Note that the map and frame limits are clamped to the range of [-86 86]
imposed by the read-only TrimLat property.
getm(gca,'MapLatLimit')
getm(gca,'FLatLimit')
getm(gca,'TrimLat')
ans =
-86.00
86.00
-86.00
86.00
-86.00
86.00
ans =
ans =
Example 3: Conic Projection
Create a map of the standard version of the Lambert Conformal Conic
projection covering latitudes 20 North to 75 North and longitudes covering 90
degrees starting at 30 degrees West.
coast = load('coast');
figure('Color','w')
axesm('lambertstd','MapLatLimit',[20 75],'MapLonLimit',[-30 60])
axis off; framem on; gridm on; mlabel on; plabel on;
geoshow(coast.lat, coast.long, 'DisplayType', 'polygon')
4-25
Creating and Viewing Maps
The call to axesm above is equivalent to:
axesm('lambertstd','Origin',[0 15 0],'FLatLimit',[20 75], ...
'FlonLimit',[-45 45])
Example 4: Southern Hemisphere Conic Projection
"Reflect" the preceding map into the Southern Hemisphere. Override the
default standard parallels as well as change MapLatLimit.
coast = load('coast');
figure('Color','w')
axesm('lambertstd','MapParallels',[-75 -15], ...
'MapLatLimit',[-75 -20],'MapLonLimit',[-30 60])
axis off; framem on; gridm on; mlabel on; plabel on;
geoshow(coast.lat,coast.long,'DisplayType','polygon')
4-26
Axes for Drawing Maps
Example 5: North-Polar Azimuthal Projection
Construct a North-polar Equal-Area Azimuthal projection map extending
from the Equator to the pole and centered by default on longitude 0.
coast = load('coast');
figure('Color','w')
axesm('eqaazim','MapLatLimit',[0 90])
axis off; framem on; gridm on; mlabel on; plabel on;
setm(gca,'MLabelParallel',0)
geoshow(coast.lat,coast.long,'DisplayType','polygon')
4-27
Creating and Viewing Maps
The call to axesm above is equivalent to:
axesm('eqaazim','MLabelParallel',0,'Origin',[90 0 0], ...
'FLatLimit',[-Inf 90])
Example 6: South-Polar Azimuthal Projection
Create a South-polar Stereographic Azimuthal projection map extending
from the South Pole to 20 degrees S, centered on longitude 150 degrees
West. Include a value for the Origin property in order to control the central
meridian.
coast = load('coast');
figure('Color','w')
axesm('stereo','Origin',[-90 -150],'MapLatLimit',[-90 -20])
axis off; framem on; gridm on; mlabel on; plabel on;
setm(gca,'MLabelParallel',-20)
geoshow(coast.lat,coast.long,'DisplayType','polygon')
4-28
Axes for Drawing Maps
The call to axesm above is equivalent to:
axesm('stereo','Origin',[-90 -150 0],'FLatLimit',[-Inf 70])
Example 7: Equatorial Azimuthal Projection
Create a map of an Equidistant Azimuthal projection with the origin on
the Equator, covering from 10 E to 170 E. The origin longitude falls at the
center of this range (90 E), and the map reaches north and south to within 10
degrees of each pole.
coast = load('coast');
figure('Color','w')
axesm('eqdazim','MapLonLimit',[10 170])
axis off; framem on; gridm on; mlabel on; plabel on;
setm(gca,'MLabelParallel',0,'PLabelMeridian',60)
geoshow(coast.lat,coast.long,'DisplayType','polygon')
4-29
Creating and Viewing Maps
The call to axesm above is equivalent to:
axesm('eqaazim','Origin',[0 90 0],'FLatLimit',[-Inf 80])
Example 8: General Azimuthal Projection
Construct an Orthographic projection map with the origin centered near
Paris. You cant use MapLatLimit or MapLonLimit in this case.
coast = load('coast');
originLat = dm2degrees([48 48]);
originLon = dm2degrees([ 2 20]);
figure('Color','w')
axesm('ortho','Origin',[originLat originLon])
axis off; framem on; gridm on; mlabel on; plabel on;
setm(gca,'MLabelParallel',30,'PLabelMeridian',-30)
geoshow(coast.lat,coast.long,'DisplayType','polygon')
4-30
Axes for Drawing Maps
Example 9: Oblique Mercator Projection
Create a map with a long, narrow, oblique Mercator projection showing the
area 10 degrees to either side of the great-circle flight path from Tokyo to New
York. You cant use MapLatLimit or MapLonLimit in this case, either.
coast = load('coast');
latTokyo = dm2degrees([ 35 40]);
lonTokyo = dm2degrees([139 45]);
latNewYork = dm2degrees([ 40 47]);
lonNewYork = dm2degrees([-73 58]);
[dist,az] = distance(latTokyo,lonTokyo,latNewYork,lonNewYork);
[midLat,midLon] = reckon(latTokyo,lonTokyo,dist/2,az);
midAz = azimuth(midLat,midLon,latNewYork,lonNewYork);
buf = [-10 10];
4-31
Creating and Viewing Maps
figure('Color','w')
axesm('mercator','Origin',[midLat midLon 90-midAz], ...
'FLatLimit',buf,'FLonLimit',[-dist/2 dist/2] + buf)
axis off; framem on; gridm on; tightmap
geoshow(coast.lat,coast.long,'DisplayType','polygon')
plotm([latTokyo latNewYork],[lonTokyo lonNewYork],'r-')
General Applicability of Map Limit Properties
As the preceding examples illustrate, most typically you use the MapLatLimit
and MapLonLimit properties to set up a map axes with a non-oblique,
non-azimuthal projection, with its origin on the Equator. (Most of the
projections included in the Mapping Toolbox fall into this category; e.g.,
cylindrical, pseudo-cylindrical, conic, or modified azimuthal.) In addition,
even with a non-zero origin latitude (origin off the Equator), you can
use the MapLatLimit and MapLonLimit properties with projections that
are implemented directly rather than via rotations of the sphere (e.g.,
tranmerc, utm, lambertstd, cassinistd, eqaconicstd, eqdconicstd, and
polyconicstd). This list includes the projections used most frequently for
large-scale maps, such as U.S. Geological Survey topographic quadrangle
maps. Finally, when the origin is located at a pole or on the Equator, you can
use the map limit properties with any azimuthal projection (e.g., stereo,
ortho, breusing, eqaazim, eqdazim, gnomonic, or vperspec).
On the other hand, you should avoid the map limit properties, working
instead with the Origin, FLatLimit, and FLonLimit properties, when:
You want your map frame to be positioned asymmetrically with respect to
the origin longitude.
You want to use an oblique aspect (that is, assign a non-zero rotation angle
to the third element of the "orientation vector" supplied as the Origin
property value).
4-32
Axes for Drawing Maps
You want to change your projections default aspect (normal vs. transverse).
You want to to use a nonzero origin latitude, except in one of the special
cases noted above.
You are using one of the following projections:
globe No need for map limits; always covers entire planet
cassini Always in a transverse aspect
wetch Always in a transverse aspect
bries Always in an oblique aspect
Theres no need to supply a value for the MapLatLimit property if youve
already supplied one for the Origin and FLatLimit properties. In fact, if
you supply all three when calling either axesm or setm, the FLatLimit value
will be ignored. Likewise, if you supply values for Origin, FLonLimit, and
MapLonLimit, the FLonLimit value will be ignored.
If you do supply a value for either MapLatLimit or MapLonLimit in one of the
situations listed above, axesm or setm will ignore it and issue a warning.
For example,
axesm('lambert','Origin',[40 0],'MapLatLimit',[20 70])
generates the warning message:
Ignoring value of MapLatLimit due to use of nonzero origin
latitude with the lambert projection.
Using the Map Limit Properties with setm
As shown in the earlier example in which the longitude limits of a map in
the Robinson projection are changed via setm, its important to understand
that MapLatLimit and MapLonLimit are extra, redundant properties that are
coupled to the Origin, FLatLimit, and FLonLimit properties. On the other
hand, its not too difficult to know how to update your map axes if you keep
in mind the following:
4-33
Creating and Viewing Maps
The Origin property takes precedence. It is set (implicitly, if not explicitly)
every time you call axesm and you cannot change it just by changing the
map limits. (Note that when creating a new map axes from scratch, the
map limits are used to help set the origin if it is not explicitly specified.)
MapLatLimit takes precedence over FLatLimit if both are provided in the
same call to axesm or setm, but changing either one alone affects the other.
MapLonLimit and FLonLimit have a similar relationship.
As shown in the example, the precedence of Origin means that if you want to
reset your map limits with setm and have setm also determine a new origin,
you must set Origin to [] in the same call. For example,
setm(gca,'Origin',[],'MapLatLimit',newMapLatlim,'MapLonLimit',newMapLonli
On the other hand, a call like this will automatically update the values of
FLatLimit and FLonLimit. Similarly, a call like:
setm(gca,'FLatLimit',newFrameLatlim,'FLonLimit',newFrameLonlim)
will update the values of MapLatLimit and MapLonLimit.
Finally, you probably dont want to try the following:
setm(gca,'Origin',[],'FLonLimit',newFrameLonlim)
because the value of FLonLimit (unlike MapLonLimit) will not affect Origin,
which will merely change to a projection-dependent default value (typically
[0 0 0]).
Switching Between Projections
Once a map axes object has been created with axesm, whether map data is
displayed or not, it is possible to change the current projection as well as many
of its parameters. You can use setm or the maptool UI to reset the projection.
The rest of this section describes the considerations and parameters involved
in switching projections in a map axes. Additional details are given for doing
this with the geoshow function in Changing Map Projections when Using
geoshow on page 4-40.
4-34
Axes for Drawing Maps
When you switch from one projection to another, setm clears out settings that
were specific to the earlier projection, updates the map frame and graticule,
and generally keeps the map covering the same part of the worldeven when
switching between azimuthal and non-azimuthal projections. But in some
cases, you might need to further adjust the map axes properties to achieve
proper appearance. Settings that are suitable for one projection might not be
appropriate for another. Most often, youll need to update the positioning of
your meridian and parallel labels.
1 Create a Mercator projection with meridian and parallel labels.
axesm mercator
framem on; gridm on; mlabel on; plabel on
setm(gca,'LabelFormat','signed')
axis off
180
150
120 90 60 30 0+ 30+ 60+ 90+120
+150
+180
+75
+60
+45
+30
+15
0
15
30
45
60
75
2 Get the default map and frame latitude limits for the Mercator projection.
4-35
Creating and Viewing Maps
[getm(gca,'MapLatLimit'); getm(gca,'FLatLimit')]
ans =
-86
86
-86
86
Both the frame and map latitude limits are set to 86 north and south for
the Mercator projection to maintain a safe distance from the singularity
at the poles.
3 Now switch the projection to an orthographic azimuthal.
setm(gca,'MapProjection','ortho')
4 Manually specify new locations for the meridian and parallel labels. (See
Labeling Grids on page 4-56.)
setm(gca,'MLabelParallel',0,'PLabelMeridian',-90,'PLabelMeridian',-30)
Now the map is displayed correctly.
4-36
Axes for Drawing Maps
+75
+90
+60
+45
+30
+15
0 60
90
30
+ 30
+ 60+ 90
15
30
45
60
75
90
Projected and Unprojected Graphic Objects
Many Mapping Toolbox cartographic functions project features on a map
axes based on their designated latitude-longitude positions. The latitudes
and longitudes are mathematically transformed to x and y positions using
the formulas for the current map projection. If the map projection or its
parameters change, objects on a map axes can be automatically reprojected
to update the map display accordingly, but only under the circumstances
detailed in the following sections.
Auto-Reprojection of Mapped Objects and Its Limitations
Using the setm function, you can change the current map projection on the fly
if the map display was created in a way that permits reprojection. Note that
map displays can contain objects that cannot be reprojected, and may need
to be explicitly deleted and redrawn. Automatic reprojection will take place
4-37
Creating and Viewing Maps
when you use setm to modify the MapProjection property, or any other map
axes property from the following list:
AngleUnits
Aspect
FalseEasting
FalseNorthing
FLatLimit
FLonLimit
Geoid
MapLatLimit
MapLonLimit
MapParallels
Origin
ScaleFactor
TrimLat
TrimLon
Zone
Auto-reprojection takes place for objects created with any of the following
Mapping Toolbox functions:
contourm
contour3m
fillm
fill3m
gridm
linem
meshm
4-38
Axes for Drawing Maps
patchm
plotm
plot3m
surfm
surfacem
textm
In general, objects created with geoshow or with a combination of calls to
mfwdtran followed by ordinary MATLAB graphics functions, such as line,
patch, or surface, are not automatically reprojected. You should delete such
objects whenever you change one or more of the map axes properties listed
above, and then redisplay them.
The above Mapping Toolbox functions are analogous to standard MATLAB
graphics functions having the same name, less the trailing m. You can use
both types of functions to plot data on a map axes, as long as you are aware
that the standard MATLAB graphics functions do not apply map projection
transformations, and therefore require you to specify positions in map x-y
space.
If you have preprojected vector or raster map data or read such data from files,
you can display it with mapshow, mapview, or standard MATLAB graphics
functions, such as plot or mesh. If its projection is known and is included
in the Mapping Toolbox projection libraries, you can use its parameters to
project geodata in geographic coordinates to display it in the same axes. For
additional information, see Using Cartesian MATLAB Display Functions
on page 6-28.
There are four common use cases for changing a map projection in a map axes
with setm or for reprojecting map data plotted on a regular MATLAB axes:
4-39
Creating and Viewing Maps
Mapping Use Case
Type of
Axes
Reprojection Behavior
Plot geographic
(latitude-longitude) vector
coordinate data or data grid
using a Mapping Toolbox
function from releases prior
to Version 2 (e.g., plotm)
Map axes
Automatic reprojection
Plot geographic vector data
with geoshow
Map axes
No automatic reprojection;
delete graphics objects prior
to changing the projection and
redraw them afterwards.
Plot data grids, images, and
contours with geographic
coordinates with geoshow
Map axes
Automatic reprojection; this
behavior could change in a
future release
Plot projected (x-y) vector
or raster map data with
mapshow or with a MATLAB
graphics function (e.g., line,
contour, or surf)
Regular
axes
Manual reprojection
(reproject coordinates with
minvtran /mfwdtran or
projinv/projfwd); delete
graphics objects prior to
changing the projection and
redraw them afterwards.
You can use handlem to help identify which objects to delete when manual
deletion is necessary. See Determining and Manipulating Object Names
on page 4-82 for an example of its use. The following section describes
reprojection behavior in more detail and illustrates some of these cases.
Changing Map Projections when Using geoshow
You can display latitude-longitude vector and raster geodata using the
geoshow function (use mapshow to display preprojected coordinates and grids).
When you use geoshow to display maps on a map axes, the data are projected
according to the map projection assigned when axesm, worldmap, or usamap
created the map axes (e.g., axesm('mapprojection','mercator')).
You can also use geoshow to display latitude-longitude data on a regular
axes (created by the axes function, for example). When you do this, the
4-40
Axes for Drawing Maps
latitude-longitude data are displayed using a Plate Carre Projection,
which linearly maps longitude to x and latitude to y.
If you are using geoshow with a map axes and want to change the map
projection after you have displayed data in geographic coordinates, do the
following, depending on whether the data are raster or vector:
Raster Data. Change the projection using setm. For example,
load geoid
figure; axesm mercator
geoshow(geoid,geoidrefvec,'DisplayType','texturemap')
setm(gca,'mapprojection','mollweid')
4-41
Creating and Viewing Maps
Vector Data. Obtain handles to the line or patch graphic objects, delete
the objects from the axes, change the projection using setm, and replot the
vector data using geoshow:
figure; axesm miller
h = geoshow('landareas.shp')
delete(h)
setm(gca,'mapprojection','ortho')
geoshow('landareas.shp')
4-42
Axes for Drawing Maps
In the above example, h is a handle to an hggroup object, which geoshow
constructs when plotting point, line, and polygon data.
If you need to change projections when displaying both raster and vector
geodata, you can combine these techniques; removing the vector graphic
objects does not affect raster data already displayed.
Placing Geographic and Nongeographic Objects in a Map Axes
Here is an example of how the two types of functions can interact when you
place text objects:
1 Make a Miller map axes with a latitude-longitude grid:
axesm miller; framem on; gridm on; mlabel on; plabel on;
showaxes; grid off;
4-43
Creating and Viewing Maps
These function calls create a map axes object, a map frame enclosing
the region of interest, and geographic grid lines. The x-y axes, which
are normally hidden, are displayed, and the axes x-y grid is turned off.
The Mapping Toolbox function gridm constructs lines to illustrate the
latitude-longitude grid, unlike the MATLAB function grid, which draws
an x-y grid for the underlying projected map coordinates. Depending on
the type of projection, a latitiude-longitude grid (or graticule) can contain
curves while a MATLAB grid never does. For more information about
graticules, see The Map Grid on page 4-53.
2 Now place a standard MATLAB text object and a mapped text object, using
the two separate coordinate systems:
text(-2,-1,'Standard text object at x = -2, y = -1')
textm(70,-150,'Mapped text object at lat = 70, lon = -150')
In the figure, shown below, a standard text object is placed at x=-2 and
y=-1, while a mapped text object is placed at (70N,150W) in the Miller
projection.
3 Now change the projection to sinusoidal. The standard text object remains
at the same Cartesian position, which alters its latitude-longitude position.
4-44
Axes for Drawing Maps
The mapped text object remains at the same geographic location, so its
x-y position is altered. Also, the frame and grid lines reflect the new map
projection:
setm(gca,'MapProjection','sinusoid')
showaxes; grid off; mlabel off
Similarly, vector and matrix data can be displayed using either mapping or
standard functions (e.g., plot/plotm, surf/surfm). See Displaying Vector
Data with Mapping Toolbox Functions on page 4-58 for information on
plotting vector geodata, and Displaying Data Grids on page 4-68 for
information on plotting raster geodata.
4-45
Creating and Viewing Maps
Controlling Map Frames and Grids
In this section...
The Map Frame on page 4-46
The Map Grid on page 4-53
The Map Frame
The Mapping Toolbox map frame is the outline of the limits of a map, often in
the form of a box, the edge of the world, so to speak. The frame is displayed
if the map axes property Frame is set to 'on'. This can be accomplished upon
map axes creation with axesm, or later with setm, or with the direct command
framem on. The frame is geographically defined as a latitude-longitude
quadrangle that is projected appropriately. For example, on a map of the
world, the frame might extend from pole to pole and a full 360 range of
longitude. In appearance, the frame would take on the characteristic shape of
the projection. The examples below are full-world frames shown in four very
different projections.
Equidistant cylindrical
projection
Robinson
projection
Sinusoidal
projection
Orthographic
projection
Full-World Map Frames
As a map object, each of the previously displayed frames is identical; however,
the selection of a display projection has varied their appearance. Because
each of the examples shows the entire world, FLatLimit is [-90 90], and
4-46
Controlling Map Frames and Grids
FLonLimit is [-180 180] for each case. The frame quadrangle can encompass
smaller regions, as well, in which case the shape is a section of a full-world
outline or simply a quadrilateral with straight or curving sides. Execute this
code to produce the figure that follows:
4-47
Creating and Viewing Maps
% Plot four regions of Robinson frame and grid using map limits
%
figure('color','white')
% Default map frame
subplot(2,2,1);
axesm('MapProjection','robinson',...
'Frame','on','Grid','on')
title('Latitude [-90 90], Map lons [-180 180]','FontSize',10)
%
subplot(2,2,2);
axesm('MapProjection','robinson',...
'MapLatLimit',[30 70],'MapLonLimit',[-90 90],...
'Frame','on','Grid','on')
title('Latitude [30 70], Longitude [-90 90]','FontSize',10)
%
subplot(2,2,3);
axesm('MapProjection','robinson',...
'MapLatLimit',[-90 0],'MapLonLimit',[-180 -30],....
'Frame','on','Grid','on')
title('Latitude [-90 0], Longitude [-180 -30]','FontSize',10)
%
subplot(2,2,4);
axesm('MapProjection','robinson',...
'MapLatLimit',[-70 -30],'MapLonLimit',[60 150],...
'Frame','on','Grid','on')
title('Latitude [-70 -30], Longitude [60 150]','FontSize',10)
4-48
Controlling Map Frames and Grids
Latitude [90 90], Map lons [180 180]
Latitude [30 70], Longitude [90 90]
Latitude [90 0], Longitude [180 30]
Latitude [70 30], Longitude [60 150]
Frame Quadrangles in the Robinson Projection (Symmetric About Prime
Meridian)
For the frames shown above, the projection is centered on the prime meridian,
or 0 longitude. Such a frame would be the result of creating a map axes with
the defaults for the Robinson projection and then resetting the frame limits to
cover just part of the world.
When you want your frame to be symmetric about the region of interest, let
axesm determine the proper settings for you. If you specify the map limits
without specifying the map origin and frame limits, axesm will automatically
set the appropriate values for a proper symmetric frame.
4-49
Creating and Viewing Maps
In the following example, the axes limits are set using setm after the Robinson
map axes is created. Note that map axes properties that concern frames begin
with F:
% Same regions as above, but with frame limits
%
altered after projecting
%
figure('color','white')
% Default frame limits
h11 = subplot(2,2,1);
axesm('MapProjection','robinson',...
'Frame','on','Grid','on')
title('Latitude [-90 90], Longitude [-180 180]')
%
h12 = subplot(2,2,2);
axesm('MapProjection','robinson',...
'Frame','on','Grid','on')
setm(h12,'FLatLimit',[30 70],'FLonLimit',[-90 90])
title('Latitude [30 70], Longitude [-90 90]')
%
h21 = subplot(2,2,3);
axesm('MapProjection','robinson',...
'Frame','on','Grid','on')
setm(h21,'FLatLimit',[-90 0],'FLonLimit',[-180 -30])
title('Latitude [-90 0], Longitude [-180 -30]')
%
h22 = subplot(2,2,4);
axesm('MapProjection','robinson',...
'Frame','on','Grid','on')
setm(h22,'FLatLimit',[-70 -30],'FLonLimit',[60 150])
title('Latitude [-70 -30], Longitude [60 150]')
4-50
Controlling Map Frames and Grids
Latitude [90 90], Longitude [180 180]
Latitude [30 70], Longitude [90 90]
Latitude [90 0], Longitude [180 30]
Latitude [70 30], Longitude [60 150]
Frame Quadrangles in the Robinson Projection (Symmetric About Map Limits)
The differences between the two examples are obvious when projections are
not centered on the prime meridian. If you wanted to create a symmetric
frame in the lower right subplot of the above figure, reset the map limits
instead of the frame limits, but be sure to reset the 'Origin' property in
the same call:
setm(h22,'MapLonLimit',[60 150],'Origin',[])
You can manipulate properties beyond the latitude and longitude limits of
the frame. Frame properties are established upon map axes object creation;
you can modify them subsequently with the setm and the framem functions.
The command framem alone is a toggle for the Frame property, which controls
4-51
Creating and Viewing Maps
the visibility of the frame. You can also call framem with property names and
values to alter the appearance of the frame:
framem('FlineWidth',4,'FEdgeColor','red')
The frame is actually a patch with a default face color set to 'none' and
a default edge color of black. You can alter these map axes properties by
manipulating the FFaceColor and FEdgeColor properties. For example, the
command
setm(gca,'FFaceColor','cyan')
makes the background region of your display resemble water. Since the frame
patch is always the lowest layer of a map display, other patches, perhaps
representing land, will appear above the water. If an object is subsequently
plotted below the frame patch, the frame altitude can be recalculated to lie
below this object with the command framem reset. The frame is replaced
and not reprojected.
Set the line width of the edge, which is 2 points by default, using the
FLineWidth property.
The primary advantage of displaying the map frame is that it can provide
positional context for other displayed map objects. For example, when vector
data of the coasts is displayed, the frame provides the edge of the world.
See the framem reference page for more details.
Map and Frame Limits
The Mapping Toolbox map and frame limits are two related map axes
properties that limit the map display to a defined region. The map latitude
and longitude limits define the extents of geodata to be displayed, while the
frame limits control how the frame fits around the displayed data. Any object
that extends outside the frame limits is automatically trimmed.
The frame limits are also specified differently from the map limits. The map
limits are in absolute geographic coordinates referenced to an origin at the
intersection of the prime meridian and the equator, while the frame limits are
referenced to the rotated coordinate system defined by the map axes origin.
4-52
Controlling Map Frames and Grids
For all nonazimuthal projections, frame limits are specified as quadrangles
([latmin latmax] and [longmin longmax]) in the frame coordinate system.
In the case of azimuthal projections, the frames are circular and are described
by a polar coordinate system. One of the frame latitude limits must be a
negative infinity (-Inf) to indicate an azimuthal frame (think of this as
the center of the circle), while the other limit determines the radius of the
circular frame (rlatmax). The longitude limits of azimuthal frames are
inconsequential, since a full circle is always displayed.
If you are uncertain about the correct format for a particular projection frame
limit, you can reset the formats to the default values using empty matrices.
Note For nonazimuthal projections in the normal aspect, the map extent is
limited by the minimum of the map limits and the frame limits; hence, the
two limits will coincide after evaluation. Therefore, if you manually change
one set of limits, you might want to clear the other set to get consistent limits.
The Map Grid
The map grid is the set of displayed meridians and parallels, also known as
a graticule. Display the grid by setting the map axes property Grid to 'on'.
You can do this when you create map axes with axesm, with setm, or with the
direct command gridm on.
Grid Spacing
To control display of meridians and parallels, set a scalar meridian spacing or
a vector of desired meridians in the MLineLocation property. The property
PLineLocation serves a corresponding purpose for parallels. The default
values place grid lines every 30 for meridians and every 15 for parallels.
4-53
Creating and Viewing Maps
Grid Layering
By default, the grid is placed as the top layer of any display. You can alter
this by changing the GAltitude property, so that other map objects can be
placed above the grid. The new grid is drawn at its new altitude. The units
used for GAltitude are specified with the daspectm function.
To reposition the grid back to the top of the display, use the command gridm
reset. You can also control the appearance of grid lines with the GLineStyle
and GLineWidth properties, which are ':' and 0.5, respectively, by default.
Limiting Grid Lines
The Miller projection is an example in which all the meridians can extend to
the poles without appearing to be cluttered. In other projections, such as
the orthographic (below), the map grid can obscure the surface where they
4-54
Controlling Map Frames and Grids
converge. Two map axes properties, MLineLimit and MLineException, enable
you to control such clutter:
Use the MLineLimit property to specify a pair of latitudes at which to
terminate the meridians. For example, setting MLineLimit to [-75
75] completely clears the region above and below this latitude range of
meridian lines.
If you want some lines to reach the poles but not others, you can specify
them with the MLineException property. For example, if MLineException
is set to [-90 0 90 180], then the meridians corresponding to the four
cardinal longitudes will continue past the limit on to the pole.
The use of these properties is illustrated in the figure below. Note that there
are two corresponding map axes properties, PLineLimit and PLineException,
for controlling the extent of displayed parallels.
4-55
Creating and Viewing Maps
Default grid allows all displayed
meridians to extend to the poles:
axesm('MapProjection','ortho',...
'Origin',[40,40,14],...
'Grid','on','Frame','on');
The property MLineLimit truncates
meridians at given latitudes:
axesm('MapProjection','ortho',...
'Origin',[40,40,14],...
'Grid','on','Frame','on',...
'MLineLimit', [-75 75]);
The property MLineLineException
permits certain meridians to extend to
the poles, regardless of MLineLimit:
axesm('MapProjection','ortho',...
'Origin',[40,40,14],...
'Grid','on','Frame','on',...
'MLineLimit', [-75 75],...
'MLineException',[-90 0 90 180]);
Labeling Grids
You can label displayed parallels and meridians. MeridianLabel and
ParallelLabel are on-off properties for displaying labels on the meridians
and parallels, respectively. They are both 'off' by default. Initially, the label
locations coincide with the default displayed grid lines, but you can alter this
by using the PlabelLocation and MlabelLocation properties. These grid
lines are labeled across the north edge of the map for meridians and along the
west edge of the map for parallels. However, the property MlabelParallel
allows you to specify 'north', 'south', 'equator', or a specific latitude at
which to display the meridian labels, and PlabelMeridian allows the choice
of 'west', 'east', 'prime', or a specific longitude for the parallel labels.
By default, parallel labels are displayed in the range of 0 to 90 north and
south of the equator while meridian labels are displayed in the range of 0 to
4-56
Controlling Map Frames and Grids
180 east and west of the prime meridian. You can use the mlabelzero22pi
function to redisplay the meridian labels in the range of 0 to 360 east of
the prime meridian.
Properties affecting grid labeling are listed below.
Property
Effect
MeridianLabel
Toggle display of meridian labels
ParallelLabel
Toggle display of parallel labels
MlabelLocation
Alternate interval for labeling meridians
PlabelLocation
Alternate interval for labeling parallels
MlabelParallel
Keyword or latitude for placing meridian
labels
PlabelMeridian
Keyword or longitude for placing parallel
labels
mlabelzero22pi(function)
Relabel meridians with positive angle from
0 to 360
For complete descriptions of all map axes properties, refer to the axesm
reference page.
4-57
Creating and Viewing Maps
Displaying Vector Data with Mapping Toolbox Functions
In this section...
Programming and Scripting Map Construction on page 4-58
Displaying Vector Data as Points and Lines on page 4-58
Displaying Vector Maps as Lines or Patches on page 4-61
Programming and Scripting Map Construction
Although mapview, maptool, and other Mapping Toolbox GUIs are convenient
and quick tools for making maps, most mapping applications require
additional effort. By using and combining Mapping Toolbox and MATLAB
functions, you can create and customize more elaborate maps interactively
by entering commands in the Command Window or by writing M-code
in functions and scripts. This section describes how to use the principal
mapping functions for displaying vector geospatial data. The following section
describes displaying raster map data.
Displaying Vector Data as Points and Lines
Mapping Toolbox vector map display of line objects works much like
MATLAB line display functions. Mapping Toolbox line graphics functions
have MATLAB analogs, the names of which can usually be determined by
appending an m to the MATLAB function name. For instance, the Mapping
Toolbox version of plot is plotm. The main difference between the two classes
of functions comes from the need for Mapping Toolbox functions to work with
geographic coordinates and map projections.
The following table lists the available Mapping Toolbox line display functions.
4-58
Function
Used For
contourm
Contour plot of map data
contour3m
Contour plot of map data in 3-D space
geoshow
High-level function to plot points, lines, patches, grids,
and georeferenced images in geocoordinates
Displaying Vector Data with Mapping Toolbox Functions
Function
Used For
linem
Draws line objects projected on map axes
mapshow
High-level function to plot points, lines, patches, grids,
and georeferenced images in plane coordinates
plotm
Clears figure and draws line objects projected on map
axes
plot3m
Projects lines on map axes in 3-D space
The following exercise shows how some of these functions work:
1 Set up a map axes and frame:
load coast
axesm mollweid
framem('FEdgeColor','blue','FLineWidth',0.5)
2 Plot the coast vector data using plotm. Just as with plot, you can specify
line property names and values in the command.
plotm(lat,long,'LineWidth',1,'Color','blue')
Sometimes vector data represents specific points. Suppose you have
variables representing the locations of Cairo (30N,32E), Rio de Janeiro
(23S,43W), and Perth (32S,116E), and you want to plot them as markers
only, without connecting line segments.
3 Define the three city geographic locations and plot symbols at them:
citylats = [30 -23 -32]; citylongs = [32 -43 116];
plotm(citylats,citylongs,'r*')
4-59
Creating and Viewing Maps
4 In addition to these sorts of permanent geographic data, you can also
display calculated vector data. Calculate and plot a great circle track from
Cairo to Rio de Janeiro, and a rhumb line track from Cairo to Perth:
[gclat,gclong] = track2('gc',citylats(1),citylongs(1),...
citylats(2),citylongs(2));
[rhlat,rhlong] = track2('rh',citylats(1),citylongs(1),...
citylats(3),citylongs(3));
plotm(gclat,gclong,'m-'); plotm(rhlat,rhlong,'m-')
4-60
Displaying Vector Data with Mapping Toolbox Functions
Note You can also use geoshow (for data in geographic coordinates) or
mapshow (for data in projected coordinates) to create such maps, either in
a map axes or in a regular axes. Both functions accept either vectors of
coordinates or geographic data structures as input data.
For more information, see Mapping Toolbox Geographic Data Structures
on page 2-16, which includes examples of creating geostructs and displaying
their contents in How to Construct Geostructs and Mapstructs on page 2-20.
Displaying Vector Maps as Lines or Patches
Vector map data that is properly formatted (i.e., as closed polygons) can be
displayed as patches, or filled-in polygons. In addition, it and other vector
data can be displayed as lines.
Note The Mapping Toolbox patch display functions differ from their MATLAB
equivalents by allowing you to display patch vector data that uses NaNs to
separate closed regions.
Vector map data for lines or polygons can be represented by simple coordinate
arrays, geostructs, or mapstructs. This example illustrates the use of
coordinate arrays for both line and polygon features as well as a geostruct
containing line features.
1 The conus (conterminous U.S.) MAT-file nicely illustrates how polygon
data is structured, manipulated, and displayed. Use who to see what it
contains before loading it.
who -file conus.mat
Your variables are:
description gtlakelon
gtlakelat
source
statelat
statelon
uslat
uslon
load conus
4-61
Creating and Viewing Maps
The variables uslat and uslon together describe three polygons (separated
by NaNs), the largest of which represents the outline of the conterminous
United States. The two smaller polygons represent Long Island, NY, and
Marthas Vineyard, an island off Massachusetts. The variables gtlakelat
and gtlakelon describe three polygons (separated by NaNs) for the Great
Lakes. The variables statelat and statelon contain line-segment data
(separated by NaNs) for the borders between states, which is not formatted
for patch display.
2 Verify that line and polygon data contains NaNs (hence multiple objects) by
typing a command similar to find(isnan(vector)):
find(isnan(gtlakelon)) %or gtlakelat
ans =
883
1058
1229
The find command returns three values indicating that the gtlakelon
(or gtlakelat) geographic coordinate arrays contain three polygons
representing one or a group of Great Lakes.
3 Read the worldrivers shapefile for the region that covers the conterminous
United States. This data, stored as a geographic data structure, is useful
for illustrating lines.
uslatlim = [min(uslat) max(uslat)]
uslatlim =
25.1200
49.3800
uslonlim = [min(uslon) max(uslon)]
uslonlim =
-124.7200
-66.9700
rivers = shaperead('worldrivers', 'UseGeoCoords', true, ...
'BoundingBox', [uslonlim', uslatlim'])
rivers =
4-62
Displaying Vector Data with Mapping Toolbox Functions
23x1 struct array with fields:
Geometry
BoundingBox
Lon
Lat
Name
4 The struct rivers is a geographic data structure having five fields. Note
that the Geometry field specifies whether the data is stored as a 'Point',
'MultiPoint', 'Line', or a 'Polygon:
rivers(1).Geometry
ans =
Line
For further details on Mapping Toolbox geographic data structures, see
Understanding Vector Geodata on page 2-13 and Understanding Raster
Geodata on page 2-33.
5 Now you can set up a map axes to display the state coordinates. As conic
projections are appropriate for mapping the entire United States, create a
map axes object using an Albers equal-area conic projection ('eqaconic').
Specifying map limits that contain the region of interest automatically
centers the projection on an appropriate longitude; the frame encloses just
the mapping area, not the entire globe. As a general rule, you should
specify map limits that extend slightly outside your area of interest
(worldmap and usamap do this for you).
Note Conic projections need two standard parallels (latitudes at which
scale distortion is zero). A good rule is to set the standard parallels at
one-sixth of the way from both latitude extremes. Or, to use default
latitudes for the standard parallels, simply provide an empty matrix in
the call to axesm.
The three options that follow demonstrate how you can set map latitude
and longitude limits to axesm:
4-63
Creating and Viewing Maps
a Obtain default latitudes by providing an empty matrix as the standard
parallels:
figure
axesm('MapProjection','eqaconic', 'MapParallels',[],...
'MapLatLimit',[23 52], 'MapLonLimit',[-130 -62])
b If you do not know what latitude and longitude limits are appropriate
for your map, as a starting point you could use the exact ones that the
geostruct contains. Using them eliminates white space around the map:
axesm('MapProjection','eqaconic', 'MapParallels',[],...
'MapLatLimit',uslatlim, 'MapLonLimit',uslonlim)
c If you want to add white space around the map, you can do so as follows
(here, 2 degrees are added):
axesm('MapProjection', 'eqaconic', 'MapParallels', [], ...
'MapLatLimit', uslatlim + [-2 2], ...
'MapLonLimit', uslonlim + [-2 2])
6 Turn on the map frame, the map grid, and the meridian and parallel labels:
axis off; framem; gridm; mlabel; plabel
The empty map looks like this.
7 When geographic data is displayed, some layers can hide others. You can
control the visibility of your map layers by varying the order in which you
4-64
Displaying Vector Data with Mapping Toolbox Functions
display them. For example, some U.S. state boundaries follow major rivers,
so display the rivers last to avoid obscuring the rivers with the boundaries.
The coordinate array pairs (uslat, uslon), (gtlakelat, gtlakelon), and
(statelat, statelon) simply contain sequences of NaN-separated map
segments, and their geometric interpretation is ambiguous. In order to
display them appropriately as either patches or lines with geoshow, you
need to use the DisplayType parameter. In contrast, DisplayType is not
needed when you map data from a geostruct like rivers.
a Plot a patch to display the area occupied by the conterminous United
States; use the geoshow function with a 'polygon' DisplayType:
geoshow(uslat,uslon, 'DisplayType','polygon','FaceColor',...
[1 .5 .3], 'EdgeColor','none')
b Plot the Great Lakes on top of the land area, using geoshow again:
geoshow(gtlakelat,gtlakelon, 'DisplayType','polygon',...
'FaceColor','cyan', 'EdgeColor','none')
c Plot the line segment data showing state boundaries, using geoshow
with a 'line' DisplayType:
geoshow(statelat,statelon,'DisplayType','line','Color','k')
d Finally, use geoshow to plot the river network. Note that you can omit
DisplayType:
geoshow(rivers, 'Color', 'blue')
4-65
Creating and Viewing Maps
Summary of Polygon Mapping Functions
The following table lists the available Mapping Toolbox patch polygon display
functions.
Function
Used For
fillm
Filled 2-D map polygons
fill3m
Filled 3-D map polygons in 3-D space
geoshow
Display map latitude and longitude data in 2-D
mapshow
Display map data without projection in 2-D
patchm
Patch objects projected on map axes
patchesm
Patches projected as individual objects on map axes
The fillm function makes use of the low-level function patchm. The toolbox
provides another patch drawing function called patchesm. The optimal use of
either depends on the application and user preferences. The patchm function
creates one displayed object and returns one handle for a patch, which can
contain multiple faces that do not necessarily connect. Mapping Toolbox data
arrays contain NaNs to separate unconnected patch faces, unlike MATLAB
patch display functions, which cannot handle NaN-delimited data for patches.
The patchesm function, on the other hand, treats each face as a separate
object and returns an array containing a handle for each patch. In general,
patchm requires more memory but is faster than patchesm. The patchesm
4-66
Displaying Vector Data with Mapping Toolbox Functions
function is useful if you need to manipulate the appearance of individual
patches (as thematic maps often require).
The geoshow and mapshow functions provide a superset of functionality
for displaying unprojected and projected geodata, respectively, in two
dimensions. These functions accept geographic data structures (geostructs
and mapstructs) and coordinate vector arrays, but can also directly read
shapefiles and geolocated raster files. With them, you can map polygon data,
controlling rendering by constructing symbolspecs, data structures that you
can construct with the makesymbolspec function. You can easily construct
symbolspecs for point and line data as well as polygon data to control its
display in geoshow, mapshow, and mapview.
Reprojectability of Maps with Vector Data. If you want to be able to
change the projection of a map on the fly, you should not use geoshow. Some
display functions, such as patchm , fillm, displaym, and linem, enable you to
reproject vector map data, but geoshow does not. That is, when you change a
map axes projection, with setm for example, vector map symbology that was
created with geoshow will not be transformed. Gridded data rendered with
geoshow (when DisplayType is surface, texturemap, or contour), however,
can be reprojected.
4-67
Creating and Viewing Maps
Displaying Data Grids
In this section...
Types of Data Grids and Raster Display Functions on page 4-68
Fitting Gridded Data to the Graticule on page 4-69
Using Raster Data to Create 3-D Displays on page 4-72
Types of Data Grids and Raster Display Functions
Mapping Toolbox functions and GUIs display both regular and geolocated
data grids originating in a variety of formats. Recall that regular data grids
require a referencing vector or matrix that describes the sampling and location
of the data points, while geolocated data grids require matrices of latitude
and longitude coordinates.
The data grid display functions are geographic analogies to the MATLAB
surface drawing functions, but operate specifically on map axes objects. Like
the line-plotting functions discussed in the previous chapter, some Mapping
Toolbox grid function names correspond to their MATLAB counterparts with
an m appended.
Note Mapping Toolbox functions beginning with mesh are used for regular
data grids, while those beginning with surf are reserved for geolocated data
grids. This usage differs from the MATLAB definition; mesh plots are used for
colored wire-frame views of the surface, while surf displays colored faceted
surfaces.
Surface map objects can be displayed in a variety of different ways. You can
assign colors from the figure colormap to surfaces according to the values
of their data. You can also display images where the matrix data consists
of indices into a colormap or display the matrix as a three-dimensional
surface, with the z-coordinates given by the map matrix. You can use
monochrome surfaces that reflect a pseudo-light source, thereby producing a
three-dimensional, shaded relief model of the surface. Finally, you can use a
combination of color and light shading to create a lighted shaded relief map.
4-68
Displaying Data Grids
The following table lists the available Mapping Toolbox surface map display
functions.
Function
Used For
geoshow
Display map data gridded in latitude and longitude in 2-D
mapshow
Display gridded map data without projection in 2-D
meshm
Regular data grid warped to projected graticule mesh
surfm
Geolocated data grid projected on map axes
pcolorm
Projected data grid in z = 0 plane
surfacem
Data grid warped to projected graticule mesh
surflm
3-D shaded surface with lighting projected on map axes
meshlsrm
3-D lighted shaded relief of regular data grid
surflsrm
3-D lighted shaded relief of geolocated data grid
Fitting Gridded Data to the Graticule
The toolbox projects surface objects in a manner similar to the traditional
methods of mapmaking. A cartographer first lays out a grid of meridians and
parallels called the graticule. Each graticule cell is a geographic quadrangle.
The cartographer calculates or interpolates the appropriate x-y locations
for every vertex in the graticule grid and draws the projected graticule by
connecting the dots. Finally, the cartographer draws the map data freehand,
attempting to account for the shape of the graticule cells, which usually
change shape across the map. Similarly, the toolbox calculates the x-y
locations of the four vertices of each graticule cell and warps or samples the
matrix data to fit the resulting quadrilateral.
In mapping data grids using the toolbox, as in traditional cartography,
the finer the mesh (analogous to using a graticule with more meridians
and parallels), the greater precision the projected map display will have,
at the cost of greater effort and time. The graticule in a printed map
is analogous to the spacing of grid elements in a regular data grid, the
Mapping Toolbox representation of which is two-element vectors of the form
[number-of-parallels, number-of-meridians]. The graticule for geolocated
data grids is similar; it is the size of the latitude and longitude coordinate
4-69
Creating and Viewing Maps
matrices: number-of-parallels = mrows-1 and number-of-meridians =
ncols-1. However, because geolocated data grids have arbitrary cell corner
locations, spacing can vary and thus their graticule is not a regular mesh.
The topo regular data grid can be displayed quickly using a coarse graticule,
at a cost of precision in terms of positioning the grid on the map. Observe the
map that results from the following commands:
% Get data grid
load topo
% Create referencing matrix
topoR = makerefmat('RasterSize', size(topo), ...
'Latlim', [-90 90], 'Lonlim', [0 360]);
% Set up Robinson proj
figure; axesm robinson
% Specify a 10x20 cell graticule
spacing = [10 20];
% Display data mapped to the graticule
h = meshm(topo,topoR,spacing);
% Set DEM color map
demcmap(topo)
4-70
Displaying Data Grids
Notice that for this coarse graticule, the edges of the map do not appear as
smooth curves. Previous displays used the default [50 100] graticule, for
which this effect is negligible.
Regardless of the graticule resolution, the grid data is unchanged. In this
case, the data grid is the 180-by-360 topo matrix, and regardless of where it
is positioned, the data values are unchanged.
Map objects displayed as surfaces have all the properties of any MATLAB
surface, which can be set at object creation or by using the MATLAB set
function. The toolbox setm function allows the MeshGrat graticule property
to be changed after a regular data grid has been displayed. Since you saved
the handle of the last displayed map, reset its graticule to a very fine grid.
Because making the mesh more precise is a trade-off of resolution versus
time and memory, doing this takes longer, and requires more memory, to
display the map:
setm(h,'MeshGrat',[200 400])
Another way you can reset a graticule is with the meshgrat function:
[latgrat,longrat] = meshgrat(topo,topoR,[200 400]);
setm(h,'Graticule',latgrat,longrat);
The vectors latgrat and longrat produced by meshgrat are vectors
containing parallel and meridian values in each mesh direction.
4-71
Creating and Viewing Maps
Notice that the result does not appear to be any better than the original
display with the default [50 100] graticule, but it took much longer to produce.
There is no point to specifying a mesh finer than the data resolution (in this
case, 180-by-360 grid cells). In practice, it makes sense to use coarse graticules
for development tasks and fine graticules for final graphics production.
Using Raster Data to Create 3-D Displays
The simplest way to display raster data is to assign colors to matrix elements
according to their data values and view them in two dimensions. Raster data
maps also can be displayed as 3-D surfaces using the matrix values as the
z data. Here you explore some basic concepts and operations for setting up
surface views, which requires explicit horizontal coordinates.
Note The difference between regular raster data and a geolocated data grid
is that each grid intersection for a geolocated grid is explicitly defined with
(x,y) or (latitude, longitude) matrices or is interpolated from a graticule,
while a regular matrix only implies these locations (which is why it needs
a georeferencing vector or matrix).
You will use the raster elevation data in the korea MAT-file, which also
includes bathymetry data for the region around the Korean peninsula, along
with a referencing vector variable, which indicates that the data set is a
regular data grid and locates it on the Earth.
1 Load the MAT-file and transform this representation to a fully geolocated
data grid by calculating a mesh via the meshgrat function:
load korea
[lat,lon] = meshgrat(map,refvec);
2 Next use the km2deg function to convert the units of elevation from meters
to degrees, so they are commensurate with the latitude and longitude
coordinate matrices:
map = km2deg(map/1000);
3 Observe the results by typing the whos command:
4-72
Displaying Data Grids
whos
Name
description
Size
2x64
Bytes
256
Class
char
lat
180x240
345600
double
lon
180x240
345600
double
map
180x240
345600
double
double
maplegend
1x3
24
refvec
1x3
24
source
2x76
304
Attributes
double
char
The lat and lon coordinate matrices form a mesh the same size as the map
matrix. This is a requirement for constructing 3-D surfaces, unlike the
example given above using the topo raster data set, which was displayed in
2-D using the meshm function. If you inspect lat and lon in the MATLAB
Variable Editor, you find that in lon, all columns contain the same number
for a given row, and in lat, all rows contain the same number for a given
column. This is because the mesh produced by meshgrat in this case is
regular, but such data grids need not have equal spacing.
4 Now set up a map axes object with the equal area conic projection:
axesm('MapProjection','eqaconic','MapParallels',[],...
'MapLatLimit',[30 45],'MapLonLimit',[115 135])
5 Instead of using the meshm function to make this map, display the korea
geolocated data grid using the surfm function, and set an appropriate
colormap:
surfm(lat,lon,map,map); demcmap(map)
tightmap
Here is the result, which is the same as what meshm would produce.
4-73
Creating and Viewing Maps
Be aware, however, that this map is really a 3-D view seen from directly
overhead (the default perspective). To appreciate that, all you need to do is
to change your viewpoint.
6 Use the view function to specify a viewing azimuth of 60 degrees (from the
east southeast) and a viewing elevation of 30 degrees above the horizon:
view(60,30)
The figure immediately rotates to the specified perspective:
4-74
Displaying Data Grids
For information on Mapping Toolbox controls over perspective map
representations or for additional help on constructing 3-D map displays, see
Chapter 5, Making Three-Dimensional Maps .
4-75
Creating and Viewing Maps
Interacting with Displayed Maps
In this section...
Picking Locations Interactively on page 4-76
Defining Small Circles and Tracks Interactively on page 4-78
Working with Objects by Name on page 4-81
Picking Locations Interactively
You can use Mapping Toolbox functions and GUIs to interact with maps,
both in mapview and in figures created with axesm. This section describes
two useful graphic input functions, inputm and gcpmap. The inputm
function (analogous to the MATLAB ginput function) allows you to get the
latitude-longitude position of a mouse click. The gcpmap function (analogous
to the MATLAB function get(gca,'CurrentPoint')) returns the current
mouse position, also in latitude and longitude.
Explore inputm with the following commands, which display a map axes with
its grid and then request three mouse clicks, the locations of which are stored
as geographic coordinates in the variable points. Then the plotm function
plots the points you clicked as red markers. The display you see depends on
the points you select:
axesm sinusoid
framem on; gridm on
points=inputm(3)
points =
-41.7177 -145.0293
7.9211
-0.5332
38.5492 149.2237
plotm(points,'r*')
4-76
Interacting with Displayed Maps
Note If you click outside the map frame, inputm returns a valid but incorrect
latitude and longitude, even though the point you indicated is off the map.
One reason you might want to manually identify points on a map is to
interactively explore how much distortion a map projection has at given
locations. For example, you can feed the data acquired with inputm to the
distortcalc function, which computes area and angular distortions at any
location on a displayed map axes. If you do so using the points variable, the
results of the previous three mouse clicks are as follows:
[areascale,angledef] = distortcalc(points(1,1),points(1,2))
areascale =
1.0000
angledef =
85.9284
>> [areascale,angledef] = distortcalc(points(2,1),points(2,2))
areascale =
1.0000
angledef =
3.1143
[areascale,angledef] = distortcalc(points(3,1),points(3,2))
areascale =
1.0000
angledef =
76.0623
4-77
Creating and Viewing Maps
This indicates that the current projection (sinusoidal) has the equal-area
property, but exhibits variable angular distortion across the map, less near
the equator and more near the poles.
To see a working application that uses the inputm function, view and run the
mapexfindcity Interactive Global City Finder demo.
Defining Small Circles and Tracks Interactively
Geographic line annotations such as navigational tracks and small circles
can be generated interactively. Great circle tracks are the shortest distance
between points, and when closed partition the Earth into equal halves; a
small circle is the locus of points at a constant distance from a reference
point. Use trackg and scircleg to create them by clicking on the map.
Double-click the tracks or circles to modify the lines. Shift+click to type
specific parameters into a control panel. The control panels also allow you
to retrieve or set properties of tracks and circles (for instance, great circle
distances and small circle radii).
The following example illustrates how to interactively create a great circle
track from Los Angeles, California, to Tokyo, Japan, and a 1000 km radius
small circle centered on the Hawaiian Islands. The track is made via the
trackg function, which prompts you to select endpoints for a track with the
mouse. The scircleg function prompts for two points also, a center and any
point on the circumference of the small circle. The specifics of the track and
the circle are then adjusted more precisely with dialog controls:
1 Set up an orthographic view centered over the Pacific Ocean. Use the
coast MAT-file:
axesm('ortho','origin',[30 180])
framem;gridm
load coast
plotm(lat,long,'k')
2 Create a track with the trackg function, which prompts for two endpoints.
The default track type is a great circle:
trackg
Track1:
4-78
Click on starting and ending points
Interacting with Displayed Maps
Click near Los Angeles and Tokyo, and the track is drawn.
3 Now create a small circle around Hawaii with the scircleg function, which
prompts for a center point and a point on the perimeter. Make the circles
radius about 2000 km, but dont worry about getting the size exact:
scircleg
Circle 1:
Click on center and perimeter
The map should look approximately like this.
4 Adjust the size of the small circle to be 2000 km by Shift+clicking anywhere
on its perimeter. The Small Circles dialog box appears.
5 Type 2000 into the Radius field.
6 Click Close. The small circle readjusts to be 2000 km around Hawaii.
7 To adjust the track between Los Angeles and Tokyo, Shift+click on it. This
brings up the Track dialog, with which you specify a position and initial
azimuth for either endpoint, as well as the length and type of the track.
4-79
Creating and Viewing Maps
8 Change the track type from Great Circle to Rhumb Line with the Track
pop-up menu. The track immediately changes shape.
9 Experiment with the other Track dialog controls. Also note that you can
move the endpoints of the track with the mouse by dragging the red circles,
and obtain the arcs length in various units of distance.
The following figure shows the Small Circles and Track dialog boxes.
Interactive Text Annotation
You can also interactively place text annotations by clicking on a map
display. The textm function, which requires numerical arguments for
locating a specified text string, was illustrated in Placing Geographic and
Nongeographic Objects in a Map Axes on page 4-43. The gtextm function,
which takes a text string and optional properties as arguments, interactively
defines the location for the specified text object based on where you click
on the map.
4-80
Interacting with Displayed Maps
Try these gtextm commands to label the locations you have just annotated:
gtextm('Hawaii','color','r')
gtextm('Tokyo')
gtextm('Los Angeles')
The following figure displays the results of these gtextm commands. After
you place text, you can move it interactively using the selection tool in the
map figure window.
Working with Objects by Name
You can manipulate displayed map objects by name. Many Mapping Toolbox
functions assign descriptive names to the Tag property of the objects they
create. The namem and related functions allow you to control the display of
groups of similarly named objects, determine the names and change them if
desired, and use the name in the Handle Graphics set and get functions.
There is also a Mapping Toolbox graphical user interface, mobjects, to help
you manage the display and control of objects.
4-81
Creating and Viewing Maps
Some mapping display functions like framem, gridm, and contourm assign
object tags by default. You can also set the name upon display by assigning
a string to the Tag property in mapping display functions that use property
name/property value pairs. If the Tag does not contain a string, the name
defaults to an objects Type property, such as 'line' or 'text'.
Determining and Manipulating Object Names
1 Display a vector map of the world:
f = axesm('fournier')
framem on; gridm on;
plabel on; mlabel('MLabelParallel',0)
load coast
plotm(lat,long,'k','Tag','Coastline')
Below is the resulting map.
2 List the names of the objects in the current axes using namem:
namem
ans =
Coastline
PLabel
MLabel
Meridian
Parallel
4-82
Interacting with Displayed Maps
Frame
3 The handlem function allows you to dereference graphic objects and to get
or set their properties. Change the line width of the coastline with set:
set(handlem('Coastline'),'LineWidth',2)
4 Change the colors of the meridian and parallel labels separately:
set(handlem('Mlabel'),'Color',[.5 .2 0])
set(handlem('Plabel'),'Color',[.2 .5 0])
You can also change these labels to be the same color using setm:
setm(f,'fontcolor', [.4 .5 .6])
5 The handlem command with no arguments summons a UI control with a list
of map axes objects. This is useful for selecting objects interactively. Try
handlem
or
h = handlem
6 Combined with set, this makes it simple to change properties such as color.
Remember, however, to use the right property name. Patches, for example,
have a FaceColor and EdgeColor, while most other objects simply have
Color, as is the case with the Coastline object. Now use handlem to call a
color picker to set the coastline to any color you like:
set(handlem,'Color',uisetcolor)
The reference page for handlem lists the object names that it recognizes.
Note that most of these names can be prefixed with all, which returns an
array of all handles for that class of object.
7 Now try handlem using the all modifier:
t = handlem('alltext')
l = handlem('allline')
Note that you can also use all with the hidem and showm functions:
4-83
Creating and Viewing Maps
hidem('alltext')
showm('alltext')
For more information on the use of functions and tools for manipulating
objects, consult the setm, getm, handlem, hidem, showm, clmo, namem, tagm,
and mobjects reference pages.
4-84
5
Making Three-Dimensional
Maps
Sources of Terrain Data on page 5-2
Reading Elevation Data Interactively on page 5-13
Determining and Visualizing Visibility Across Terrain on page 5-19
Shading and Lighting Terrain Maps on page 5-22
Draping Data on Elevation Maps on page 5-40
Working with the Globe Display on page 5-49
Making Three-Dimensional Maps
Sources of Terrain Data
In this section...
Digital Terrain Elevation Data from NGA on page 5-2
Digital Elevation Model Files from USGS on page 5-3
Determining What Elevation Data Exists for a Region on page 5-3
Digital Terrain Elevation Data from NGA
Nearly all published terrain elevation data is in the form of data grids.
Displaying Data Grids on page 4-68 described basic approaches to rendering
surface data grids with Mapping Toolbox functions, including viewing surfaces
in 3-D axes. The following sections describe some common data formats for
terrain data, and how to access and prepare data sets for particular areas of
interest.
The Digital Terrain Elevation Data (DTED) Model is a series of gridded
elevation models with global coverage at resolutions of 1 kilometer or finer.
DTEDs are products of the U. S. National Geospatial Intelligence Agency
(NGA), formerly the National Imagery and Mapping Agency (NIMA), and
before that, the Defense Mapping Agency (DMA). The data is provided as
1-by-1 degree tiles of elevations on geographic grids with product-dependent
grid spacing. In addition to NGAs own DTEDs, terrain data from Shuttle
Radar Topography Mission (SRTM), a cooperative project between NASA and
NGA, are also available in DTED format, levels 1 and 2 (see below).
The lowest resolution data is the DTED Level 0, with a grid spacing of 30
arc-seconds, or about 1 kilometer. The DTED files are binary. The files have
filenames with the extension dtN, where N is the level of the DTED product.
You can find published specifications for DTED at the NGA web site.
NGA also provides higher resolution terrain data files. DTED Level 1 has a
resolution of 3 arc-seconds, or about 100 meters, increasing to 18 arc-seconds
near the poles. It was the primary source for the USGS 1:250,000 (1 degree)
DEMs. Level 2 DTED files have a minimum resolution of 1 arc-second near
the equator, increasing to 6 arc-seconds near the poles. DTED files are
available on from several sources on CD-ROM, DVD, and on the Internet.
5-2
Sources of Terrain Data
Note For information on locating map data for download over the
Internet, see the following documentation at the MathWorks Web site:
http://www.mathworks.com/support/tech-notes/2100/2101.html.
Digital Elevation Model Files from USGS
The United States Geological Survey (USGS) has prepared terrain data grids
for the U.S. suitable for use at scales between 1:24,000 and 1:250,000 and
beyond. Some of this data originated from Defense Mapping Agency DTEDs.
Specifications and data quality information are available for these digital
elevation models (DEMs) and other U.S. National Mapping Program geodata
from the USGS. USGS no longer directly distributes 1:24,000 DEMs and other
large-scale geodata. U.S. DEM files in SDTS format are available from private
vendors, either for a fee or at no charge, depending on the data sets involved.
The largest scale USGS DEMs are partitioned to match the USGS 1:24,000
scale map series. The grid spacing for these elevations models is 30 meters
on a Universal Transverse Mercator grid. Each file covers a 7.5-minute
quadrangle. (Note, however, that only a subset of paper quadrangle maps are
projected with UTM, and that USGS vector geodata products might not use
this coordinate system.) The map and data series is available for much of the
conterminous United States, Hawaii, and Puerto Rico.
Determining What Elevation Data Exists for a Region
Several Mapping Toolbox functions and a GUI help you identify file names for
and manage digital elevation model data for areas of interest. These tools do
not retrieve data from the Internet; however, they do locate files that lie on
the Mapping Toolbox path and indicate the names of data sets that you can
download or order on magnetic media or CD-ROM.
Certain Mapping Toolbox utility functions can describe and import elevation
data. The following table describes functions that read in data, determine
what file names might exist for a given area, or return metadata for elevation
grid files. These files are data products packaged by government agencies;
with minor exceptions, the format used for each is unique to that data
product, which is why special functions are required to read them and why
their filenames and/or footprints can be known a priori.
5-3
Making Three-Dimensional Maps
Function to Read
Files
Function to Identify
or Summarize Files
U.S. Department
of Defense Digital
Terrain Elevation
Data
dted
dteds
DEM
USGS 1-degree
(3-arc-second
resolution) digital
elevation models
usgsdem
usgsdems
DEM24K
USGS 1:24K
(30-meter resolution)
digital elevation
models
usgs24kdem
N/A
ETOPO5 ETOPO2
Earth Topography 5minute (ETOPO5) and
2-minute (ETOPO2)
etopo
N/A
GTOPO30
Tiles of 30-arc-second
global elevation
models
gtopo30
gtopo30s
SATBATH
Global 2-minute
(4 km) satellite
topography and
bathymetry data
satbath
N/A
SDTS DEM
Digital elevation
models in U.S. SDTS
format
sdtsdemread
sdtsinfo (reads
metadata from catalog
file)
TBASE
TerrainBase
topography and
bathymetry binary
and ASCII grid files
tbase
N/A
File Type
Description
DTED
Note that the names of functions that identify file names are those of their
respective file-reading functions appended with s. These functions determine
file names for areas of interest, and have calling arguments of the form
(latlim, lonlim), with which you indicate the latitude and longitude limits
5-4
Sources of Terrain Data
for an area of interest, and all return a list of filenames that provide the
elevations required. The southernmost latitude and the western-most
longitude must be the first numbers in latlim and lonlim, respectively.
Using dteds, usgsdems, and gtopo30s to Identify DEM Files
Suppose you want to obtain elevation data for the area around Cape Cod,
Massachusetts. You define your area of interest to extend from 41.1N to
43.9N latitude and from 71.9W to 69.1W longitude.
1 To determine which DTED files you need, use the dteds function, which
returns a cell array of strings:
dteds([41.1 43.9],[-71.9 -69.1])
ans =
'\DTED\W072\N41.dt0'
'\DTED\W071\N41.dt0'
'\DTED\W070\N41.dt0'
'\DTED\W072\N42.dt0'
'\DTED\W071\N42.dt0'
'\DTED\W070\N42.dt0'
'\DTED\W072\N43.dt0'
'\DTED\W071\N43.dt0'
'\DTED\W070\N43.dt0'
Note three important considerations about using DTED files:
a DTED filenames reflect latitudes only and thus do not uniquely specify
a data set; they must be organized within directories that specify
longitudes. When you download level 0 DTEDs, the DTED directory and
its subdirectories are transferred as a compressed archive that you must
decompress before using.
b Some files that the dteds function identifies do not exist, either because
they completely cover water bodies or have never been created or
released by NGA. The dted function that reads the DTEDs handles
missing cells appropriately.
c NGA might or might not continue to make DTED data sets
available to the general public online. For information on
availability of terrain data from NGA and other sources, see
http://www.mathworks.com/support/tech-notes/2100/2101.html.
5-5
Making Three-Dimensional Maps
2 To determine the USGS DEM files you need, use the usgsdems function:
usgsdems([41.1 43.9],[-71.9 -69.1])
ans =
'portland-w'
'portland-e'
'bath-w'
'boston-w'
'boston-e'
'providence-w'
'providence-e'
'chatham-w'
Note that, in contrast to the dteds command you executed above, there
are eight rather than nine files listed to cover the 3-by-3-degree region of
interest. The cell that consists entirely of ocean has no name and is thus
omitted from the output cell array.
3 To determine the GTOPO30 files you need, use the gtopo30s function:
gtopo30s([41.1 43.9],[-71.9 -69.1])
ans =
'w100n90'
Note The DTED, GTOPO30, and small-scale (low-resolution) USGS DEM
grids are in latitude and longitude. Large-scale (24K) USGS DEMs grids are
in UTM coordinates. The usgs24kdem function automatically unprojects the
UTM grids to latitude and longitude; the stdsdemread function does not.
For additional information, see the reference pages for dteds, usgsdems,
usgs24kdem, and gtopo30s.
Mapping a Single DTED File with the DTED Function
In this exercise, you render DTED level 0 data for a portion of Cape Cod. The
1-by-1 file can be downloaded from NGA or purchased on CD-ROM. You
read and display the elevation data at full resolution as a lighted surface to
show both large- and small-scale variations in the data.
5-6
Sources of Terrain Data
1 Define the area of interest and determine the file to be obtained:
latlim = [ 41.20 41.95];
lonlim = [-70.95 -70.10];
2 To determine which DTED files you need, use the dteds function, which
returns a cell array of strings:
dteds(latlim, lonlim)
ans =
'dted\w071\n41.dt0'
In this example, only one DTED file is needed, so the answer is a single
string. For more information on the dteds function, see Using dteds,
usgsdems, and gtopo30s to Identify DEM Files on page 5-5).
3 Unless you have a CD-ROM containing this file, download it from the
source indicated in the following tech note:
http://www.mathworks.com/support/tech-notes/2100/2101.html
The original data comes as a compressed tar or zip archive that you must
expand before using.
4 Use the dted function to create a terrain grid and a referencing vector
in the workspace at full resolution. If more than one DTED file named
n41.dt0 exists on the path, your working directory must be /dted/w071 in
order to be sure that dted finds the correct file. If the file is not on the path,
you are prompted to navigate to the n41.dt0 file by the dted function:
samplefactor = 1;
[capeterrain, caperef] = dted('n41.dt0', ...
samplefactor, latlim, lonlim);
5 Because DTED files contain no bathymetric depths, decrease elevations of
zero slightly to render them with blue when the colormap is reset:
capeterrain(capeterrain == 0) = -1;
6 Use usamap to construct an empty map of axes for the region defined by
the latitude and longitude limits:
5-7
Making Three-Dimensional Maps
figure;
ax = usamap(latlim,lonlim);
7 Read data for the region defined by the latitude and longitude limits from
the usastatehi shapefile:
capecoast = shaperead('usastatehi',...
'UseGeoCoords', true,...
'BoundingBox', [lonlim' latlim']);
8 Display coastlines on the map axes that was created with usamap:
geoshow(ax, capecoast, 'FaceColor', 'none');
At this point the map looks like this:
9 Render the elevations, and set the colormap accordingly:
meshm(capeterrain, caperef, size(capeterrain), capeterrain);
demcmap(capeterrain)
The resulting map, shown below, is a window on Cape Cod, and illustrates
the relative coarseness of DTED level 0 data.
5-8
Sources of Terrain Data
Mapping Multiple DTED Files with the DTED Function
When your region of interest extends across more than one DTED tile, the
dted function concatenates the tiles into a single matrix, which can be at full
resolution or a sample of every nth row and column. You can specify a single
DTED file, a directory containing several files (for different latitudes along
a constant longitude), or a higher level directory containing subdirectories
with files for several longitude bands.
1 To follow this exercise, you need to acquire the necessary DTED files from
the Internet as described in the following tech note
http://www.mathworks.com/support/tech-notes/2100/2101.html
or from a CD-ROM. This yields a set of directories that contain the
following files:
/dted
/w070
n41.avg
n41.dt0
n41.max
n41.min
n43.avg
5-9
Making Three-Dimensional Maps
n43.dt0
n43.max
n43.min
/w071
n41.avg
n41.dt0
n41.max
n41.min
n42.avg
n42.dt0
n42.max
n42.min
n43.avg
n43.dt0
n43.max
n43.min
/w072
n41.avg
n41.dt0
n41.max
n41.min
n42.avg
n42.dt0
n42.max
n42.min
n43.avg
n43.dt0
n43.max
n43.min
2 Change your working directory to the directory that includes the top-level
DTED directory (which is always named dted).
3 Use the dted function, specifying that directory as the first argument:
latlim = [ 41.1 43.9];
lonlim = [-71.9 -69.1];
samplefactor = 5;
[capetopo,caperef] = dted(pwd, samplefactor, latlim, lonlim);
5-10
Sources of Terrain Data
The sample factor value of 5 specifies that only every fifth data cell, in both
latitude and longitude, will be read from the original DTED file. You can
choose a larger value to save memory and speed processing and display, at
the expense of resolution and accuracy. The size of your elevation array
(capetopo) will be inversely proportional to the square of the sample factor.
Note You can specify a DTED filename rather than a directory name if
you are accessing only one DTED file. If the file cannot be found, a file
dialog is presented for you to navigate to the file you want. See the example
Mapping a Single DTED File with the DTED Function on page 5-6.
4 As DTEDs contain no bathymetric depths, recode all zero elevations to -1,
to enable water areas to be rendered properly:
capetopo(capetopo==0)=-1;
5 Obtain the elevation grids latitude and longitude limits; use them to draw
an outline map of the area to orient the viewer:
[latlim,lonlim] = limitm(capetopo,caperef);
figure;
ax = usamap(latlim,lonlim);
capecoast = shaperead('usastatehi',...
'UseGeoCoords', true,...
'BoundingBox', [lonlim' latlim']);
geoshow(ax,capecoast,'FaceColor','None');
The map now looks like this.
5-11
Making Three-Dimensional Maps
6 Render the elevation grid with meshm, and then recolor the map with
demcmap to display hypsometric colors (elevation tints):
meshm(capetopo, caperef, size(capetopo), capetopo);
demcmap(capetopo)
Here is the map; note the missing tile to the right where no DTED data exists.
5-12
Reading Elevation Data Interactively
Reading Elevation Data Interactively
Extracting DEM Data with demdataui
You can browse many formats of digital elevation map data using the
demdataui graphical user interface. The demdataui GUI determines
and graphically depicts coverage of ETOPO5, TerrainBase, the satellite
bathymetry model (SATBATH), GTOPO30, GLOBE, and DTED data sets on
local and network file systems, and can import these files into the workspace.
Note When it opens, demdataui scans your Mapping Toolbox path for
candidate data files. On PCs, it also checks the root directories of CD-ROMs
and other drives, including mapped network drives. This can cause a delay
before the GUI appears.
You can choose to read from any of the data sets demdataui has located. If
demdataui does not recognize data you think it should find, check your path
and click Help to read about how files are identified.
This exercise illustrates how to use the demdataui interface. You will not
necessarily have all the DEM data sets shown in this example. Even if you
have only one (the DTED used in the previous exercise, for example), you can
still follow the steps to obtain your own results:
1 Open the demdataui UI. It scans the path for data before it is displayed:
demdataui
5-13
Making Three-Dimensional Maps
The Source list in the left pane shows the data sets that were found. The
coverage of each data set is indicated by a yellow tint on the map with gray
borders around each tile of data. Here, the source is selected to present
all DTED files available to a user.
2 Clicking a different source in the left column updates the coverage display.
Here is the coverage area for available GTOPO30 tiles.
5-14
Reading Elevation Data Interactively
3 Use the map in the UI to specify the location and density of data to extract.
To interactively set a region of interest, click in the map to zoom by a factor
of two centered on the cursor, or click and drag across the map to define a
rectangular region. The size of the matrix of the area currently displayed is
printed above the map. To reduce the amount of data, you can continue to
zoom in, or or you can raise the Samplefactor slider. A sample factor of 1
reads every point, 2 reads every other point, 3 reads every third point, etc.
The matrix size is updated when you move the Samplefactor slider.
Here is the UI panel after selecting ETOPO30 data and zooming in on the
Indian subcontinent.
5-15
Making Three-Dimensional Maps
4 To see the terrain you have windowed at the sample factor you specified,
click the Get button. This causes the GUI map pane to repaint to display
the terrain grid with the demcmap colormap. In this example, the data grid
contains 580-by-568 data values, as shown below.
5-16
Reading Elevation Data Interactively
5 If you are not satisfied with the result, click the Clear button to remove all
data previously read in via Get and make new selections. You might need
to close and reopen demdatui in order to select a new region of interest.
6 When you are ready to import DEM data to the workspace or save it as a
MAT-file, click the Save button. Select a destination and name the output
variable or file. You can save to a MAT-file or to a workspace variable.
The demdataui function returns one or more matrices as an array of
display structures, having one element for each separate get you requested
(assuming you did not subsequently Clear). You then use geoshow or
mlayers to add the data grids to a map axes.
The data returned by demdataui contains display structures. You
cannot update these to geographic data structures (geostructs) using the
updategeostruct function, because they are of type surface, which the
updating function does not recognize. However, you can still display them
with geoshow, as shown in the next step.
5-17
Making Three-Dimensional Maps
7 To access the contents of the display structure, use its field names. Here
map and maplegend are copied from the structure and used to create a
lighted three-dimensional elevation map display using worldmap. (demdata
is the default name for the structure, which you can override when you
save it.)
Z = demdata.map;
refvec = demdata.maplegend;
figure
ax = worldmap(Z, refvec);
geoshow(ax, Z, refvec, 'DisplayType', 'texturemap');
axis off
demcmap(Z);
5-18
Determining and Visualizing Visibility Across Terrain
Determining and Visualizing Visibility Across Terrain
Computing Line of Sight with los2
You can use regular data grids of elevation data to answer questions about
the mutual visibility of locations on a surface (intervisibility). For example,
Is the line of sight from one point to another obscured by terrain?
What area can be seen from a location?
What area can see a given location?
The first question can be answered with the los2 function. In its simplest
form, los2 determines the visibility between two points on the surface of a
digital elevation map. You can also specify the altitudes of the observer and
target points, as well as the datum with respect to which the altitudes are
measured. For specialized applications, you can even control the actual and
effective radius of the Earth. This allows you to assume, for example, that
the Earth has a radius 1/3 larger than its actual value, which is a model
frequently used in predicting radio wave propagation.
The following example shows a line-of-sight calculation between two points
on a regular data grid generated by the peaks function. The calculation is
performed by the los2 function, which returns a logical result: 1 (points are
intervisible), or 0 (points are not intervisible).
1 Create an elevation grid using peaks with a maximum elevation of 500,
and set its origin at (0N, 0W), with a spacing of 1000 cells per degree):
map = 500*peaks(100);
maplegend = [ 1000 0 0];
2 Define two locations on this grid to test intervisibility:
lat1 = -0.027; lon1 = 0.05; lat2 = -0.093; lon2 = 0.042;
3 Calculate intervisibility. The final argument specifies the altitude (in
meters) above the surface of the first location (lat1, lon1) where the
observer is located (the viewpoint):
los2(map,maplegend,lat1,lon1,lat2,lon2,100)
5-19
Making Three-Dimensional Maps
ans =
1
The los2 function also produces a profile diagram in a figure window showing
visibility at each grid cell along the line of sight that can be used to interpret
the Boolean result. In this example, the diagram shows that the line between
the two locations just barely clears an intervening peak.
You can also compute the viewshed, a name derived from watershed, which
is all of the areas that are visible from a particular location. The viewshed
function can be thought of as performing the los2 line-of-sight calculation
from one point on a digital elevation map to every other entry in the matrix.
The viewshed function supports the same options as los2.
The following shows which parts of the peaks elevation map in the previous
example are visible from the first point:
[vismap,vismapleg] = viewshed(map,maplegend,lat1,lon1,100);
5-20
Determining and Visualizing Visibility Across Terrain
5-21
Making Three-Dimensional Maps
Shading and Lighting Terrain Maps
In this section...
Lighting a Terrain Map Constructed from a DTED File on page 5-22
Lighting a Global Terrain Map with lightm and lightmui on page 5-25
Surface Relief Shading on page 5-29
Colored Surface Shaded Relief on page 5-33
Relief Mapping with Light Objects on page 5-36
Lighting a Terrain Map Constructed from a DTED File
The lightm function creates light objects in the current map. To modify the
positions and colors of lights created on world maps or large regions you
can use the interactive lightmui GUI. For finer control over light position
(for example, in small areas lit by several lights), you have to specify light
positions using projected coordinates. This is because lights are children of
axes and share their coordinate space. See Lighting a Global Terrain Map
with lightm and lightmui on page 5-25 for an example of using lightmui.
In this exercise, you manually specify the position of a single light in the
northwest corner of a DTED DEM for Cape Cod.
1 To illustrate lighting terrain maps, begin by following the exercise in
Mapping a Single DTED File with the DTED Function on page 5-6, or
execute the steps below:
latlim = [ 41.20 41.95];
lonlim = [-70.95 -70.10];
cd dted\w071 %Note: Your absolute path may vary
samplefactor = 1;
[capeterrain, caperef] = dted('n41.dt0', samplefactor,...
latlim, lonlim);
capeterrain(capeterrain == 0) = -1;
capecoast = shaperead('usastatehi',...
'UseGeoCoords', true,...
'BoundingBox', [lonlim' latlim']);
5-22
Shading and Lighting Terrain Maps
2 Construct a map of the region within the specified latitude and longitude
limits:
figure
ax = usamap(latlim,lonlim);
geoshow(ax, capecoast, 'FaceColor', 'none');
geoshow(ax, capeterrain, caperef, 'DisplayType', 'mesh');
demcmap(capeterrain)
The map looks like this.
3 Set the vertical exaggeration. Use daspectm to specify that elevations are
in meters and should be multiplied by 20:
daspectm('m',20)
4 Make sure that the line data is visible. To ensure that it is not obscured by
terrain, use zdatam to set it to the highest elevation of the cape1 terrain
data:
zdatam('allline',max(capeterrain(:)))
5 Specify a location for a light source with lightm:
h = lightm(42,-71);
5-23
Making Three-Dimensional Maps
If you omit arguments, a GUI for setting positional properties for the new
light opens.
6 To see the properties of light objects, inspect the handle returned by lightm:
get(h)
Position = [-0.00616097 0.796039 1]
Color = [1 1 1]
Style = infinite
BeingDeleted = off
ButtonDownFcn =
Children = []
Clipping = on
CreateFcn =
DeleteFcn =
BusyAction = queue
HandleVisibility = on
HitTest = on
Interruptible = on
Parent = [138.001]
Selected = off
SelectionHighlight = on
Tag =
Type = light
UIContextMenu = []
UserData = [ (1 by 1) struct array]
Visible = on
Had you used the MATLAB light function in place of lightm, you would
have needed to specify the position in Cartesian 3-space.
7 The lighting computations caused the map to become quite dark with
specular highlights. Now restore its luminance by specifying three surface
reflectivity properties in the range of 0 to 1:
ambient = 0.7; diffuse = 1; specular = 0.6;
material([ambient diffuse specular])
5-24
Shading and Lighting Terrain Maps
The surface looks blotchy because there is no interpolation of the lighting
component (flat facets are being modeled). Correct this by specifying Phong
shading:
lighting phong
The map now looks like this.
8 If you want to compare the lit map with the unlit version, you can toggle
the lighting off:
lighting none
For additional information, see the reference pages for daspectm, lightm,
light, lighting, and material.
Lighting a Global Terrain Map with lightm and
lightmui
In this example, you create a global topographic map and add a local light at
a distance of 250 km above New York City, (40.75 N, 73.9 W). You then
change the material and lighting properties, add a second light source, and
activate the lightmui tool to change light position, altitude, and colors.
The lightmui display plots lights as circular markers whose facecolor
indicates the light color. To change the position of a light, click and drag the
5-25
Making Three-Dimensional Maps
circular marker. Alternatively, right-clicking the circular marker summons a
dialog box for changing the position or color of the light object. Clicking the
color bar in that dialog box invokes the uisetcolor dialog box that can be
used to specify or pick a color for the light.
1 Load the topo DTM files, and set up an orthographic projection:
load topo
axesm ('mapprojection','ortho', 'origin',[10 -20 0])
2 Plot the topography and assign a topographic colormap:
meshm(topo,topolegend);
demcmap(topo)
3 Set up a yellow light source over New York City:
hl = lightm(40.75,-73.9, 500/almanac('earth','radius'),...
'color','yellow', 'style', 'local');
The first two arguments to lightm are the latitude and longitude of the
light source. The third argument is its altitude, in units of Earth radii (in
this case they are in kilometers, the default units of almanac).
4 The surface is quite dark, so give it more reflectivity by specifying
material([0.7270 1.5353 1.9860
lighting phong; hidem(gca)
4.0000
The lighted orthographic map looks like this.
5-26
0.9925]);
Shading and Lighting Terrain Maps
5 If you want, add more lights, as follows:
h2 = lightm(20,40, .1,'color','magenta', 'style', 'local')
The second light is magenta, and positioned over the Gulf of Arabia.
6 To modify the lights, use the lightmui GUI, which lets you drag lights
across a world map and specify their color and altitudes:
lightmui(gca)
The lights are shown as appropriately colored circles, which you can drag to
new positions. You can also Ctrl+click a circle to bring up a dialog box for
directly specifying that lights position, altitude, and color. The GUI and
the map look like this at this point.
5-27
Making Three-Dimensional Maps
7 In the lightmui window, drag the yellow light to the eastern tip of Brazil,
and drag the magenta light to the Straits of Gibraltar.
8 Ctrl+click or Shift+click the magenta circle in the lightmui window. A
second UI, for setting light position and color, opens. Set the altitude
to 0.04 (Earth radii). Set the light color components to 1.0 (red), 0.75
(green), and 1.0 (blue). Press Return after each action. The colorbar on the
UI changes to indicate the color you set. If you prefer to pick a color, click
on the colorbar to bring up a color-choosing UI. The map now looks like this.
5-28
Shading and Lighting Terrain Maps
For additional information, see the reference pages for lightm and lightmui.
Surface Relief Shading
You can make dimensional monochrome shaded-relief maps with the function
surflm, which is analogous to the MATLAB surfl function. The effect of
surflm is similar to using lights, but the function models illumination itself
(with one light source that you specify when you invoke it, but cannot
reposition) by weighting surface normals rather than using light objects.
Shaded relief maps of this type are usually portrayed two-dimensionally
rather than as perspective displays. The surflm function works with any
projection except globe.
The surflm function accepts geolocated data grids only. Recall, however, that
regular data grids are a subset of geolocated data grids, to which they can be
converted using meshgrat (see Fitting Gridded Data to the Graticule on
page 4-69). The following example illustrates this procedure.
Creating Monochrome Shaded Relief Maps Using surflm
As stated above, surflm simulates a single light source instead of inserting
light objects in a figure. Conduct the following exercise with the korea data
set to see how surflm behaves. It uses worldmap to set up an appropriate map
axes and reference outlines.
5-29
Making Three-Dimensional Maps
1 Set up a projection and display a vector map of the Korean peninsula
with worldmap:
figure;
ax = worldmap('korea');
latlim = getm(ax,'MapLatLimit');
lonlim = getm(ax,'MapLonLimit');
coastline = shaperead('landareas',...
'UseGeoCoords', true,...
'BoundingBox', [lonlim' latlim']);
geoshow(ax, coastline, 'FaceColor', 'none');
worldmap chooses a projection and map bounds to make this map.
2 Load the korea terrain model:
load korea
3 Generate the grid of latitudes and longitudes to transform the regular
data grid to a geolocated one:
5-30
Shading and Lighting Terrain Maps
[klat,klon] = meshgrat(map,refvec);
4 Use surflm to generate a default shaded relief map, and change the
colormap to a monochromatic scale, such as gray, bone, or copper.
ht = surflm(klat,klon,map);
colormap('copper')
In this default case, the lighting direction is set at 45 counterclockwise
from the viewing direction; thus the sun is in the southeast. This map
is shown below.
5 To make the light come from some other direction, specify the light sources
azimuth and elevation as the fourth argument to surflm. Clear the terrain
map and redraw it, specifying an azimuth of 135 (northeast) and an
elevation of 60 above the horizon:
clmo(ht); ht=surflm(klat,klon,map,[135,60]);
The surface lightens and has a new character because it is lit closer to
overhead and from a different direction.
5-31
Making Three-Dimensional Maps
6 Now shift the light to the northwest (-135 azimuth), and lower it to 40
above the horizon. Because a lower sun decreases the overall reflectance
when viewed from straight above, also specify a more reflective surface
as a fifth argument to surflm. This is a 1-by-4 vector describing relative
contributions of ambient light, diffuse reflection, specular reflection, and a
specular shine coefficient. It defaults to [.55 .6 .4 10].
clmo(ht); ht=surflm(klat,klon,map,[-135, 30],[.65 .4 .3 10]);
This is a good choice for lighting this terrain, because of the predominance
of mountain ridges that run from northeast to southwest, more or less
perpendicular to the direction of illumination. Here is the final map.
5-32
Shading and Lighting Terrain Maps
For further information, see the reference pages for surflm and surfl.
Shaded relief representations can highlight the fine structure of the land
and sea floor, but because of the monochromatic coloration, it is difficult to
distinguish land from sea. The next section describes how to color such maps
to set off land from water.
Colored Surface Shaded Relief
The functions meshlsrm and surflsrm display maps as shaded relief with
surface coloring as well as light source shading. You can think of them as
extensions to surflm that combine surface coloring and surface light shading.
Use meshlsrm to display regular data grids and surflsrm to render geolocated
data grids.
These two functions construct a new colormap and associated CData matrix
that uses grayscales to lighten or darken a matrix component based on its
calculated surface normal to a light source. While there are no analogous
MATLAB display functions that work like this, you can obtain similar results
using MATLAB light objects, as Relief Mapping with Light Objects on page
5-36 explains.
5-33
Making Three-Dimensional Maps
Coloring Shaded Relief Maps and Viewing Them in 3-D
In this exercise, you use surflsrm in a way similar to how you used surflm
in the preceding exercise, Creating Monochrome Shaded Relief Maps Using
surflm on page 5-29. In addition, you set a vertical scale and view the map
from various perspectives.
1 Start with a new map axes and the korea data, and then georeference
the regular data grid:
load korea
[klat,klon] = meshgrat(map,refvec);
axesm miller
2 Create a colormap for DEM data; it is transformed by surflsm to shade
relief according to how you specify the suns altitude and azimuth:
[cmap,clim] = demcmap(map);
3 Plot the colored shaded relief map, specifying an azimuth of -135 and an
altitude of 50 for the light source:
surflsrm(klat,klon,map,[-130 50],cmap,clim)
You can also achieve the same effect with meshlsrm, which operates
on regular data grids (it first calls meshgrat, just as you just did), e.g.,
meshlsrm(map,maplegend).
4 The surface has more contrast than if it were not shaded, and it might help
to lighten it uniformly by 25% or so:
brighten(.25)
The map, which has an overhead view, looks like this.
5-34
Shading and Lighting Terrain Maps
5 Plot an oblique view of the surface by hiding its bounding box, exaggerating
terrain relief by a factor of 50, and setting the view azimuth to -30
(south-southwest) and view altitude to 30 above the horizon:
set(gca,'Box','off')
daspectm('meters',50)
view(-30,30)
The map now looks like this.
6 You can continue to rotate the perspective with the view function (or
interactively with the Rotate 3D tool in the figure window), and to
change the vertical exaggeration with the daspectm function. You cannot
5-35
Making Three-Dimensional Maps
change the built-in lighting direction without generating a new view using
surflsrm.
For further information, see the reference pages for surflsrm, meshlsrm,
daspectm, and view.
Relief Mapping with Light Objects
In the exercise Lighting a Global Terrain Map with lightm and lightmui on
page 5-25, you created light objects to illuminate a Globe display. In the
following one, you create a light object to mimic the map produced in the
previous exercise (Coloring Shaded Relief Maps and Viewing Them in 3-D on
page 5-34), which uses shaded relief computations rather than light objects.
The meshlsrm and surflsrm functions simulate lighting by modifying the
colormap with bands of light and dark. The map matrix is then converted to
indices for the new shaded colormap based on calculated surface normals.
Using light objects allows for a wide range of lighting effects. The toolbox
manages light objects with the lightm function, which depends upon the
MATLAB light function. Lights are separate MATLAB graphic objects, each
with its own object handle.
Colored 3-D Relief Maps Illuminated with Light Objects
As a comparison to the lighted shaded relief example shown earlier, add a
light source to the surface colored data grid of the Korean peninsula region:
1 If you need to, load the korea DEM, and create a map axes using the
Miller projection:
load korea
figure; axesm('MapProjection','miller',...
'MapLatLimit',[30 45],'MapLonLimit',[115 135])
2 Display the DEM with meshm, and color it with terrain hues:
meshm(map,refvec,size(map),map);
demcmap(map)
The map, without lighting effects, looks like this.
5-36
Shading and Lighting Terrain Maps
3 Create a light object with lightm (similar to the MATLAB light function,
but specifies position with latitude and longitude rather than x, y, z). The
light is placed at the northwest corner of the grid, one degree high:
h=lightm(45,115,1)
The figure becomes darker.
4 To see any relief in perspective, it is necessary to exaggerate the vertical
dimension. Use a factor of 50 for this:
daspectm('meters',50)
The figure becomes darker still, with highlights at peaks.
5 Set the ambient (direct), diffuse (skylight), and specular (highlight) surface
reflectivity characteristics, respectively:
material ([.7, .9, .8])
6 By default, the lighting is flat (plane facets). Change this to Phong shading
(interpolated normal vectors at facet corners):
lighting phong
The map now looks like this.
5-37
Making Three-Dimensional Maps
7 Finally, remove the edges of the bounding box and set a viewpoint of -30
azimuth, 30 altitude:
set(gca,'Box','off')
view(-30,30)
The view from (-30,30) with one light at (45,115,1) and Phong shading
is shown below. Compare it to the final map in the previous exercise,
Coloring Shaded Relief Maps and Viewing Them in 3-D on page 5-34.
To remove a light (when there is only one) from the current figure, type
5-38
Shading and Lighting Terrain Maps
clmo(handlem('light'))
For more information, consult the reference pages for lightm, daspectm,
material, lighting, and view, along with the section on Lighting as a
Visualization Tool in the 3D Visualization documentation.
5-39
Making Three-Dimensional Maps
Draping Data on Elevation Maps
In this section...
Draping Geoid Heights over Topography on page 5-40
Draping Data over Terrain with Different Gridding on page 5-43
Draping Geoid Heights over Topography
Lighting effects can provide important visual cues when elevation maps are
combined with other kinds of data. The shading resulting from lighting a
surface makes it possible to drape satellite data over a grid of elevations.
It is common to use this kind of display to overlay georeferenced land cover
images from Earth satellites such as LANDSAT and SPOT on topography
from digital elevation models. Mapping Toolbox displays use variations of
techniques described in the previous section.
When the elevation and image data grids correspond pixel-for-pixel to the
same geographic locations, you can build up such displays using the optional
altitude arguments in the surface display functions. If they do not, you can
interpolate one or both source grids to a common mesh.
The following example shows the figure of the Earth (the geoid data set)
draped on topographic relief (the topo data set). The geoid data is shown as
an attribute (using a color scale) rather than being depicted as a 3-D surface
itself. The two data sets are both 1-by-1-degree meshes sharing a common
origin.
Note The geoid can be described as the surface of the ocean in the absence
of waves, tides, or land obstructions. It is influenced by the gravitational
attraction of denser or lighter materials in the Earths crust and interior and
by the shape of the crust. A model of the geoid is required for converting
ellipsoidal heights (such as might be obtained from GPS measurements) to
orthometric heights. Geoid heights vary from a minimum of about 105 meters
below sea level to a maximum of about 85 meters above sea level.
1 Begin by loading the topo and geoid regular data grids:
5-40
Draping Data on Elevation Maps
load topo
load geoid
2 Create a map axes using a Gall stereographic cylindrical projection (a
perspective projection):
axesm gstereo
3 Use meshm to plot a colored display of the geoids variations, but specify
topo as the final argument, to give each geoid grid cell the height (z-value)
of the corresponding topo grid cell:
meshm(geoid,geoidrefvec,size(geoid),topo)
Low geoid heights are shown as blue, high ones as red.
4 For reference, plot the world coastlines in black, raise their elevation to
1000 meters (high enough to clear the surface in their vicinity), and expand
the map to fill the frame:
load coast
plotm(lat,long,'k')
zdatam(handlem('allline'),1000)
tightmap
At this point the map looks like this.
5-41
Making Three-Dimensional Maps
5 Due to the vertical view and lack of lighting, the topographic relief
is not visible, but it is part of the figures surface data. Bring it
out by exaggerating relief greatly, and then setting a view from the
south-southeast:
daspectm('m',200); tightmap
view(20,35)
6 Remove the bounding box, shine a light on the surface (using the default
position, offset to the right of the viewpoint), and render again with Phong
shading:
set(gca,'Box','off')
camlight;
lighting phong
7 Finally, set the perspective to converge slightly (the default perspective
is orthographic):
set(gca,'projection','perspective')
The final map is shown below. From it, you can see that the geoid mirrors
the topography of the major mountain chains such as the Andes, the
5-42
Draping Data on Elevation Maps
Himalayas, and the Mid-Atlantic Ridge. You can also see that large areas
of high or low geoid heights are not simply a result of topography.
Draping Data over Terrain with Different Gridding
If you want to combine elevation and attribute (color) data grids that cover
the same region but are gridded differently, you must resample one matrix to
be consistent with the other. It helps if at least one of the grids is a geolocated
data grid, because their explicit horizontal coordinates allow them to be
resampled using the ltln2val function. To combine dissimilar grids, you
can do one of the following:
Construct a geolocated grid version of the regular data grid values.
Construct a regular grid version of the geolocated data grid values.
The following two examples illustrate these closely related approaches.
Draping via Converting a Regular Grid to a Geolocated Data
Grid
This example drapes slope data from a regular data grid on top of elevation
data from a geolocated data grid. Although the two data sets actually have
the same origin (the geolocated grid derives from the topo data set), this
approach works with any dissimilar grids. The example uses the geolocated
data grid as the source for surface elevations and transforms the regular data
grid into slope values, which are then sampled to conform to the geolocated
5-43
Making Three-Dimensional Maps
data grid (creating a set of slope values for the diamond-shaped grid) and
color-coded for surface display.
Note When you use ltln2val to resample a regular data grid over an
irregular area, make sure that the regular data grid completely covers the
area of the geolocated data grid.
1 Begin by loading the geolocated data grids from mapmtx, which contains two
regions. You will only use the diamond-shaped portion of mapmtx (lt1, lg1,
and map1) centered on the Middle East, not the lt2, lg2, and map1 data:
load mapmtx lt1
load mapmtx lg1
load mapmtx map1
Load the topo global regular data grid:
load topo
2 Compute surface aspect, slope, and gradients for topo. You use only the
slopes in subsequent steps:
[aspect,slope,gradN,gradE] = gradientm(topo,topolegend);
3 Use ltln2val to interpolate slope values to the geolocated grid specified
by lt1, lg1:
slope1 = ltln2val(slope,topolegend,lt1,lg1);
The output is a 50-by-50 grid of elevations matching the coverage of the
map1 variable.
4 Set up a figure with a Miller projection and use surfm to display the slope
data. Specify the z-values for the surface explicitly as the map1 data, which
is terrain elevation:
figure; axesm miller
surfm(lt1,lg1,slope1,map1)
5-44
Draping Data on Elevation Maps
The map mainly depicts steep cliffs, which represent mountains (the
Himalayas in the northeast), and continental shelves and trenches.
5 The coloration depicts steepness of slope. Change the colormap to make
the steepest slopes magenta, the gentler slopes dark blue, and the flat
areas light blue:
colormap cool;
6 Use view to get a southeast perspective of the surface from a low viewpoint:
view(20,30); daspectm('m',200)
In 3-D, you immediately see the topography as well as the slope.
7 The default rendering uses faceted shading (no smooth interpolation).
Render the surface again, this time making it shiny with Phong shading
and lighting from the east (the default of camlight lights surfaces from
over the viewers right shoulder):
material shiny;camlight;lighting phong
8 Finally, remove white space and re-render the figure in perspective mode:
axis tight; set(gca,'Projection','Perspective')
Here is the mapped result.
5-45
Making Three-Dimensional Maps
Draping a Geolocated Grid on Regular Data Grid via Texture
Mapping
The second way to combine a regular and a geolocated data grid is to construct
a regular data grid of your geolocated data grids z-data. This approach has
the advantage that more computational functions are available for regular
data grids than for geolocated ones. Another aspect is that the color and
elevation grids do not have to be the same size. If the resolutions of the two
are different, you can create the surface as a three-dimensional elevation
map and later apply the colors as a texture map. You do this by setting the
surface Cdata property to contain the color matrix, and setting the surface
face color to 'TextureMap'.
In the following steps, you create a new regular data grid that covers the
region of the geolocated data grid, then embed the color data values into the
new matrix. The new matrix might need to have somewhat lower resolution
than the original, to ensure that every cell in the new map receives a value.
1 Load the topo and terrain data from mapmtx:
load
load
load
load
5-46
topo;
mapmtx lt1
mapmtx lg1
mapmtx map1
Draping Data on Elevation Maps
2 Identify the geographic limits of one of the mapmtx geolocated grids:
latlim = [min(lt1(:)) max(lt1(:))];
lonlim = [min(lg1(:)) max(lg1(:))];
3 Trim the topo data to the rectangular region enclosing the smaller grid:
[topo1,topo1ref] = maptrims(topo,topolegend,latlim,lonlim);
4 Create a regular grid filled with NaNs to receive texture data:
[curve1,curve1ref] = nanm(latlim,lonlim,.5);
The last parameter establishes the grid at 1/.5 cells per degree.
5 Use imbedm to embed values from map1 into the curve1 grid; the values are
the discrete Laplacian transform (the difference between each element of
the map1 grid and the average of its four orthogonal neighbors):
curve1 = imbedm(lt1,lg1,del2(map1),curve1,curve1ref);
6 Set up a map axes with the Miller projection and use meshm to draw the
topo1 extract of the topo DEM:
figure; axesm miller
h = meshm(topo1,topo1ref,size(topo1),topo1);
7 Render the figure as a 3-D view from a 20 azimuth and 30 altitude, and
exaggerate the vertical dimension by a factor of 200:
view(20,30); daspectm('m',200)
8 Light the view and render with Phong shading in perspective:
material shiny; camlight; lighting phong
axis tight; set(gca,'Projection','Perspective')
So far, both the surface relief and coloring represent topographic elevation.
5-47
Making Three-Dimensional Maps
9 Apply the curve1 matrix as a texture map directly to the figure using the
set function:
set(h,'Cdata',curve1,'FaceColor','TextureMap')
The area originally covered by the [lt1, lg1, map1] geolocated data grid,
and recoded via the Laplacian transform as curve1, now controls color
symbolism, with the NaN-coded outside cells rendered in black.
5-48
Working with the Globe Display
Working with the Globe Display
In this section...
What Is the Globe Display? on page 5-49
The Globe Display Compared with the Orthographic Projection on page
5-50
Using Opacity and Transparency in Globe Displays on page 5-52
Over-the-Horizon 3-D Views Using Camera Positioning Functions on
page 5-55
Displaying a Rotating Globe on page 5-57
What Is the Globe Display?
The Globe display is a three-dimensional view of geospatial data capable
of mapping terrain relief or other data for an entire planet viewed from
space. Its underlying transformation maps latitude, longitude, and elevation
to a three-dimensional Cartesian frame. All Mapping Toolbox projections
transform latitudes and longitudes to map x- and y-coordinates. The globe
function is special because it can render relative relief of elevations above,
below, or on a sphere. In Earth-centered Cartesian (x,y,z) coordinates, z is not
an optional elevation; rather, it is an axis in Cartesian three-space. globe is
useful for geospatial applications that require three-dimensional relationships
between objects to be maintained, such as when one simulates flybys, and/or
views planets as they rotate.
The Globe display is based on a coordinate transformation, and is not a map
projection. While it has none of the distortions inherent in planar projections,
it is a three-dimensional model of a planet that cannot be displayed without
distortion or in its entirety. That is, in order to render the globe in a figure
window, either a perspective or orthographic transformation must be applied,
both of which necessarily involve setting a viewpoint, hiding the back side
and distortions of shape, scale, and angles.
5-49
Making Three-Dimensional Maps
The Globe Display Compared with the Orthographic
Projection
The following example illustrates the differences between the two-dimensional
orthographic projection, which looks spherical but is really flat, and the
three-dimensional Globe display. Use the Rotate 3D tool to manipulate the
display.
1 Load the topo data set and render it with an orthographic map projection:
load topo
axesm ortho; framem
meshm(topo,topolegend);demcmap(topo)
2 View the map obliquely:
view(3); daspectm('m',1)
3 You can view it in 3-D from any perspective, even from underneath. To
visualize this, define a geolocated data grid with meshgrat, populate it with
a constant z-value, and render it as a stem plot with stem3m:
[latgrat,longrat] = meshgrat(topo,topolegend,[20 20]);
stem3m(latgrat,longrat,500000*ones(size(latgrat)),'r')
Use the Rotate 3D tool on the figure window toolbar to change your
viewpoint. No matter how you position the view, you are looking at a disc
with stems protruding perpendicularly.
5-50
Working with the Globe Display
4 Create another figure using the Globe transform rather than orthographic
projection:
figure
axesm('globe','Geoid',almanac('earth','radius','m'))
5 Display the topo surface in this figure and view it in 3-D:
meshm(topo,topolegend); demcmap(topo)
view(3)
6 Include the stem plot to visualize the difference in surface normals on a
sphere:
stem3m(latgrat,longrat,500000*ones(size(latgrat)),'r')
7 You can apply lighting to the display, but its location is fixed, and does not
move as the camera position is shifted:
camlight('headlight','infinite')
8 If you prefer a more unobstructed view, hide the 3-D axes:
set(gca,'Box','off')
Here is a representative view using the Globe display with the headlight.
5-51
Making Three-Dimensional Maps
You can use the LabelRotation property when you use the Orthographic or
any other Mapping Toolbox projection to align meridian and parallel labels
with the graticule. Because the Globe display is not a true map projection and
is handled differently internally, LabelRotation does not work with it.
For additional information on functions used in this example, see the
reference pages for view, camlight, meshgrat, and stem3m.
Using Opacity and Transparency in Globe Displays
Because Globe displays depict 3-D objects, you can see into and through
them as long as no opaque surfaces (e.g., patches or surfaces) obscure your
view. This can be particularly disorienting for point and line data, because
features on the back side of the world are reversed and can overlay features
on the front side.
Here is one way to create an opaque surface over which you can display line
and point data:
1 Create a figure and set up a Globe display:
5-52
Working with the Globe Display
figure; axesm('globe')
2 Draw a graticule in a light color, slightly raised from the surface:
gridm('GLineStyle','-','Gcolor',[.8 .7 .6],'Galtitude', .02)
3 Load and plot the coast data in black, and set up a 3-D perspective:
load coast
plot3m(lat,long,.01,'k')
view(3)
4 Use the Rotate 3D tool on the figures toolbar to rotate the view. Note how
confusing the display is because of its transparency.
5 Make a uniform 1-by-1-degree grid and a referencing matrix for it:
base = zeros(180,360);
baseR = makerefmat('RasterSize', size(base), ...
'ColumnsStartFrom', 'north', 'RowsStartFrom', 'west');
5-53
Making Three-Dimensional Maps
6 Render the grid onto the globe, color it copper, light it from camera right,
and make the surface reflect more light:
hs = meshm(base,baseR,size(base));
colormap copper
camlight right
material([.8 .9 .4])
Note Another way to make the surface of the globe one color is to change
the FaceColor property of a displayed surface mesh (e.g., topo).
If you havent rotated it, the display looks like this.
When you manually rotate this map, its movement can be jerky due to the
number of vectors that must be redisplayed. In any position, however, the
copper surface effectively hides all lines on the back side of the globe.
5-54
Working with the Globe Display
Note The technique of using a uniform surface to hide rear-facing lines has
limitations for the display of patch symbolism (filled polygons). As patch
polygons are represented as planar, in three-space the interiors of large
patches can intersect the spherical surface mesh, allowing its symbolism
to show through.
Over-the-Horizon 3-D Views Using Camera
Positioning Functions
You can create dramatic 3-D views using the Globe display. The camtargm and
camposm functions (Mapping Toolbox functions corresponding to camtarget
and campos) enable you to position focal point and a viewpoint, respectively,
in geographic coordinates, so you do not need to deal with 3-D Cartesian
figure coordinates.
In this exercise, you display coastlines from the landareas shapefile over
topographic relief, and then view the globe from above Washington, D.C.,
looking toward Moscow, Russia.
1 Set up a Globe display and obtain topographic data for the map:
figure
axesm globe
load topo
2 Display topo without the vertical component (by omitting the fourth
argument to meshm):
meshm(topo, topolegend, size(topo)); demcmap(topo);
The default view is from above the North Pole with the central meridian
running parallel to the x-axis.
3 Add world coastlines from the global landareas shapefile and plot them
in light gray:
coastlines = shaperead('landareas',...
'UseGeoCoords', true, 'Attributes', {});
plotm([coastlines.Lat], [coastlines.Lon], 'Color', [.7 .7 .7])
5-55
Making Three-Dimensional Maps
4 Read the coordinate locations for Moscow and Washington from the
worldcities shapefile:
moscow = shaperead('worldcities',...
'UseGeoCoords', true,...
'Selector',{@(name) strcmpi(name,'Moscow'), 'Name'});
washington = shaperead('worldcities',...
'UseGeoCoords', true,...
'Selector',{@(name) strcmpi(name,'Washington D.C.'),...
'Name'});
5 Create a great circle track to connect Washington with Moscow and plot
it in red:
[latc,lonc] = track2('gc',...
moscow.Lat, moscow.Lon, washington.Lat, washington.Lon);
plotm(latc,lonc,'r')
6 Point the camera at Moscow. Wherever the camera is subsequently moved,
it always looks toward [moscow.Lat moscow.Lon]:
camtargm(moscow.Lat, moscow.Lon, 0)
7 Station the camera above Washington. The third argument is an altitude
in Earth radii:
camposm(washington.Lat, washington.Lon, 3)
8 Establish the camera up vector with the camera targets coordinates. The
great circle joining Washington and Moscow now runs vertically:
camupm(moscow.Lat, moscow.Lon)
9 Set the field of view for the camera to 20 for the final view:
camva(20)
10 Add a light, specify a relatively nonreflective surface material, and hide
the map background:
camlight; material(0.6*[ 1 1 1])
hidem(gca)
5-56
Working with the Globe Display
Here is the final view.
For additional information, see the reference pages for extractm, camtargm,
camposm, camupm, globe, and camlight.
Displaying a Rotating Globe
Because the Globe display can be viewed from any angle without the need to
recompute a projection, you can easily animate it to produce a rotating globe.
If the displayed data is simple enough, such animations can be redrawn at
relatively fast rates. In this exercise, you progressively add or replace features
on a Globe display and rotate it under the control of an M-file that resets the
view to rotate the globe from west to east in one-degree increments.
1 In the Mapping Toolbox editor, create an M-file containing the following
code:
% spin.m: Rotates a view around the equator one revolution
% in 5-degree steps. Negative step makes it rotate normally
% (west-to-east).
for i=360:-5:0
view(i,23.5);
% Earth's axis tilts by 23.5 degrees
drawnow
end
Save this as spin.m in your current directory or on the Mapping Toolbox
path. Note that the azimuth parameter for the figure does not have the
same origin as geographic azimuth: it is 90 degrees to the west.
5-57
Making Three-Dimensional Maps
2 Set up a Globe display with a graticule, as follows:
axesm('globe','Grid','on','Gcolor',[.7 .8 .9],'GlineStyle','-')
The view is from above the North Pole.
3 Show the axes, but hide the edges of the figures box, and view it in
perspective rather than orthographically (the default perspective):
set(gca, 'Box','off', 'Projection','perspective')
4 Spin the globe one revolution with your M-file:
spin
The globe spins rapidly. The last position looks like this.
5 To make the globe opaque, create a sea-level data grid as you did for the
previous exercise, Using Opacity and Transparency in Globe Displays
on page 5-52:
5-58
Working with the Globe Display
base = zeros(180,360); baseref = [1 90 0];
hs = meshm(base,baseref,size(base));
colormap copper
The globe now is a uniform dark copper color with the grid overlaid.
6 Pop up the grid so it appears to float 2.5% above the surface. Prevent the
display from stretching to fit the window with the axis vis3d command:
setm(gca, 'Galtitude',0.025);
axis vis3d
7 Spin the globe again:
spin
The motion is slower, due to the need to rerender the 180-by-360 mesh: The
last frame looks like this.
5-59
Making Three-Dimensional Maps
8 Get ready to replace the uniform sphere with topographic relief by deleting
the copper mesh:
clmo(hs)
load topo
9 Scale the elevations to have an exaggeration of 50 (in units of Earth radii)
and plot the surface:
topo = topo / (almanac('earth','radius')* 20);
hs = meshm(topo,topolegend,size(topo),topo);
demcmap(topo)
5-60
Working with the Globe Display
10 Show the Earth in space; blacken the figure background, turn off the three
axes, and spin again:
set(gcf,'color','black');
axis off;
spin
Here is a representative view, showing the Himalayas rising on the Eastern
limb of the planet and the Andes on the Western limb.
11 You can apply lighting as well, which shifts as the planet rotates. Try the
following settings, or experiment with others:
5-61
Making Three-Dimensional Maps
camlight right
lighting phong;
material ([.7, .9, .8])
Here is the illuminated version of the preceding view:
For additional information, see the globe, camlight, and view reference
pages.
5-62
6
Customizing and Printing
Maps
Inset Maps on page 6-2
Graphic Scales on page 6-8
North Arrows on page 6-14
Thematic Maps on page 6-17
Using Cartesian MATLAB Display Functions on page 6-28
Using Colormaps and Colorbars on page 6-34
Printing Maps to Scale on page 6-45
Customizing and Printing Maps
Inset Maps
Inset maps are often used to display widely separated areas, generally at the
same scale, or to place a map in context by including overviews at smaller
scales. You can create inset maps by nesting multiple axes in a figure and
defining appropriate map projections for each. To ensure that the scale of
each of the maps is the same, use axesscale to resize them. As an example,
create an inset map of California at the same scale as the map of South
America, to relate the size of that continent to a more familiar region:
1 Begin by defining a map frame for South America using worldmap:
figure
h1 = worldmap('south america');
2 Use shaperead to read the demo world land areas polygon shapefile:
6-2
Inset Maps
land = shaperead('landareas.shp', 'UseGeoCoords', true);
3 Display the data in the map axes:
geoshow([land.Lat],[land.Lon])
setm(h1,'FFaceColor','w') % set the frame fill to white
4 Place axes for an inset in the lower middle of the map frame, and project a
line map of California:
h2 = axes('pos',[.5 .2 .1 .1]);
CA = shaperead('usastatehi', 'UseGeoCoords', true, ...
'Selector', {@(name) isequal(name,'California'), 'Name'});
usamap('california')
geoshow([CA.Lat],[CA.Lon])
6-3
Customizing and Printing Maps
5 Set the frame fill color and set the labels:
setm(h2,'FFaceColor','w')
mlabel; plabel; gridm % toggle off
6 Make the scale of the inset axes, h2 (California), match the scale of the
original axes, h1 (South America). Hide the map border:
axesscale(h1)
set([h1 h2], 'Visible', 'off')
6-4
Inset Maps
Note that the toolbox software chose a different projection and appropriate
parameters for each region based on its location and shape. You can
override these choices to make the two projections the same.
7 Find out what map projections are used, and then make South Americas
projection the same as Californias:
getm(h1, 'mapprojection')
ans =
eqdconic
getm(h2, 'mapprojection')
ans =
lambert
setm(h1, 'mapprojection', getm(h2, 'mapprojection'))
6-5
Customizing and Printing Maps
Note that the parameters for South America defaulted properly (those
appropriate for California were not used).
8 Finally, experiment with changing properties of the inset, such as its color:
setm(h2, 'ffacecolor', 'y')
6-6
Inset Maps
6-7
Customizing and Printing Maps
Graphic Scales
Graphic scale elements are used to provide indications of size even more
frequently than insets are. These are ruler-like objects that show distances on
the ground at the nominal scale of the projection. You can use the scaleruler
function to add a graphic scale to the current map. You can check and modify
the scaleruler settings using getm and setm. You can also move the graphic
scale to a new position by dragging its baseline.
Try this by creating a map, adding a graphic scale with the default settings,
and shifting its location. Then add a second scale in nautical miles, and
change the tick mark style and direction:
1 Use usamap to plot a map of Texas and surrounding states as filled polygons:
states = shaperead('usastatehi.shp', 'UseGeoCoords', true);
usamap('Texas')
faceColors = makesymbolspec('Polygon',...
{'INDEX', [1 numel(states)], ...
'FaceColor', polcmap(numel(states))});
geoshow(states,'DisplayType', 'polygon',...
'SymbolSpec', faceColors)
Because polcmap randomizes patch colors, your display can look different.
6-8
Graphic Scales
2 Add a default graphic scale and then move it to a new location:
scaleruler on
setm(handlem('scaleruler1'),'YLoc',.5)
The units of scaleruler default to kilometers. Note that handlem accepts
the keyword 'scaleruler' or 'scaleruler1' for the first scaleruler,
'scaleruler2' for the second one, etc. If there is more than one scaleruler
on the current axes, specifying the keyword 'scaleruler' returns a vector
of handles.
6-9
Customizing and Printing Maps
3 Obtain a handle to the scalerulers hggroup using handlem and inspect its
properties using getm:
s = handlem('scaleruler');
getm(s)
ans =
Azimuth: 0
Children: 'scaleruler1'
Color: [0 0 0]
FontAngle: 'normal'
FontName: 'Helvetica'
FontSize: 9
FontUnits: 'points'
FontWeight: 'normal'
Label: ''
Lat: 19.07296767149959
Long: 24.00830075180499
LineWidth: 0.50000000000000
MajorTick: [0 100 200 300 400 500]
MajorTickLabel: {6x1 cell}
MajorTickLength: 20
6-10
Graphic Scales
MinorTick:
MinorTickLabel:
MinorTickLength:
Radius:
RulerStyle:
TickDir:
TickMode:
Units:
XLoc:
YLoc:
ZLoc:
[0 25 50 75 100]
'100'
12.50000000000000
'earth'
'ruler'
'up'
'auto'
'km'
0.15000000000000
0.50000000000000
[]
4 Change the scalerulers font size to 8 points:
setm(s,'fontsize',8)
5 Place a second graphic scale, this one in units of nautical miles:
scaleruler('units','nm')
6 Modify its tick properties:
setm(handlem('scaleruler2'), 'YLoc', .48,...
'MajorTick', 0:100:300,...
'MinorTick', 0:25:50, 'TickDir', 'down',...
'MajorTickLength', km2nm(25),...
'MinorTickLength', km2nm(12.5))
6-11
Customizing and Printing Maps
7 Experiment with the two other ruler styles available:
setm(handlem('scaleruler1'), 'RulerStyle', 'lines')
setm(handlem('scaleruler2'), 'RulerStyle', 'patches')
6-12
Graphic Scales
6-13
Customizing and Printing Maps
North Arrows
The north arrow element provides the orientation of a map by pointing to
the geographic North Pole. You can use the northarrow function to display
a symbol indicating the direction due north on the current map. The north
arrow symbol can be repositioned by clicking and dragging its icon. The
orientation of the north arrow is computed, and does not need manual
adjustment no matter where you move the symbol. Ctrl+clicking the icon
creates an input dialog box with which you can change the location of the
north arrow:
1 To illustrate the use of north arrows, create a map centered at the South
Pole and add a north arrow symbol at a specified geographic position:
Antarctica = shaperead('landareas', 'UseGeoCoords', true, ...
'Selector',{@(name) strcmpi(name,{'Antarctica'}), 'Name'});
figure;
worldmap('south pole')
geoshow(Antarctica)
northarrow('latitude', -57, 'longitude', 135);
6-14
North Arrows
2 Click and drag the north arrow symbol to another corner of the map. Note
that it always points to the North Pole.
3 Drag the north arrow back to the top left corner.
4 Right-click or Ctrl+click the north arrow. The Inputs for North Arrow
dialog opens, which lets you specify the line weight, edge and fill colors,
and relative size of the arrow. Set some properties and click OK.
5 Also set some north arrow properties manually, just to get a feel for them:
h = handlem('NorthArrow');
set(h, 'FaceColor', [1.000 0.8431 0.0000],...
'EdgeColor', [0.0100 0.0100 0.9000])
6 Make three more north arrows, to show that from the South Pole, every
direction is north:
northarrow('latitude',-57,'longitude', 45);
northarrow('latitude',-57,'longitude',225);
northarrow('latitude',-57,'longitude',315);
6-15
Customizing and Printing Maps
Note North arrows are created as objects in the MATLAB axes (and thus
have Cartesian coordinates), not as mapping objects. As a result, if you create
more than one north arrow, any Mapping Toolbox function that manipulates
a north arrow will affect only the last one drawn.
6-16
Thematic Maps
Thematic Maps
In this section...
What Is a Thematic Map? on page 6-17
Choropleth Maps on page 6-18
Special Thematic Mapping Functions on page 6-23
What Is a Thematic Map?
Most published and online maps fall into four categories:
Navigation maps, including topographic maps and nautical and
aeronautical charts
Geophysical maps, that show the structure and dynamics of earth, oceans
and atmosphere
Location maps, that depict the locations and names of physical features
Thematic maps, that portray attribute data about locations and features
Although online maps often combine these categories in new and unexpected
ways, published maps and atlases tend to respect them.
Thematic maps tend to be more highly stylized than other types of maps and
frequently omit locational information such as place names, physical features,
coordinate grids, and map scales. This is because rather than showing
physical features on the ground, such as shorelines, roads, settlements,
topography, and vegetation, a thematic map displays quantified facts (a
theme), such as statistics for a region or sets of regions. Examples include
the locations of traffic accidents in a city, or election results by state.
Thematic maps have a wide vocabulary of cartographic symbols, such as
point symbols, dot distributions, quiver vectors, isolines, colored zones,
raised prisms, and continuous 3-D surfaces. Mapping Toolbox functions can
generate most of these types of map symbology.
6-17
Customizing and Printing Maps
Choropleth Maps
The most familiar form of thematic map is probably the choropleth map
(from the Greek choros, for place, and plethos, for magnitude). Often used to
present data in newspapers, magazines, and reports, choropleth maps fill
geographic zones (such as countries or states, but also matrices) with colors
and/or patterns to represent nominal, ordinal, or cardinal data values. As
there are usually more possible data values than unique symbols or colors
capable of differentiating them, choropleth maps usually classify their data
into value ranges.
Mapping Toolbox choropleth maps are constructed with patch objects . It
assigns a color to each patch face to represent a specified variable, one value
per patch. When the variable is scalar (as opposed to nominal) it generally
represents a density (such as population per unit area), intensity (such as
income per family), or incidence rate (such as fatalities per thousand persons).
It can also convey extensive measurements or counts (such as electoral votes
per state) if used carefully.
To make a choropleth map you need to input or compute a vector of values,
one for each patch in a vector data set. Symbolizing such data values with
the toolbox is straightforward. It involves assigning the data values to the
CData property of a set of patches, and then setting up a colormap with an
appropriate color scheme and range. Colormaps usually map N or fewer
values (for N patches) to M colors. M can be any number between 2 and N,
but typically ranges between 5 and 10.
In the following example, patches representing the 50 states of the U.S.
(and the District of Columbia) are displayed and colored according to the
surface areas calculated by the areaint function. An equal-area projection is
appropriate for this and other choropleth maps. This is because data is often
computed or normalized over the patches being displayed, and thus area
distortion should be minimized, even at the expense of shape distortion.
1 Import low-resolution U.S. state boundary polygons:
states = shaperead('usastatelo', 'UseGeoCoords', true);
This data set includes patch data for individual states, the United States,
and its Great Lakes.
6-18
Thematic Maps
2 Set up map axes with a projection suitable to display all 50 states with
equal areas, a graticule, and grid labels:
axesm('MapProjection', 'eqaconic', 'MapParallels', [],...
'MapLatLimit', [15 75], 'MapLonLimit', [-175 -60],...
'MLineLocation', 15, 'MLabelParallel', 'south',...
'MeridianLabel', 'on', 'ParallelLabel', 'on',...
'GLineStyle', '-', 'GColor' , 0.5*[1 1 1],...
'Grid', 'on', 'Frame', 'on')
3 Draw the polygon map in the state structure using face colors randomly
selected by polcmap:
faceColors = makesymbolspec('Polygon',...
{'INDEX', [1 numel(states)], 'FaceColor', ...
polcmap(numel(states))});
geoshow(states, 'DisplayType', 'polygon', ...
'SymbolSpec', faceColors)
6-19
Customizing and Printing Maps
4 Choose an ellipsoid for computing spherical area:
wgs84 = almanac('earth', 'geoid', 'kilometers', 'grs80');
5 Add a 'SurfaceArea' field to the states geostruct, and assign surface areas
in square kilometers for each U.S. state plus D.C. with a for loop:
for k = 1:numel(states)
states(k).SurfaceArea = sum(areaint(states(k).Lat, ...
states(k).Lon, wgs84));
end
maxarea = max([states.SurfaceArea]);
6 Redisplay the states based on the surface area. Use a monotonic colormap
from red to yellow.
surfaceColors = makesymbolspec('Polygon',...
{'SurfaceArea', [0 maxarea], ...
'FaceColor', autumn(numel(states))});
geoshow(states, 'DisplayType', 'polygon', ...
'SymbolSpec', surfaceColors)
title('State Surface Area in Square Kilometers')
6-20
Thematic Maps
7 Show a colorbar as a key to the symbology, in its default location. This
legend relates patch color to area in square km:
caxis([0 maxarea])
colormap('autumn')
colorbar
6-21
Customizing and Printing Maps
8 The map is mostly red, as the above figure shows. Experiment with other
colormaps. Some names of predefined colormaps are autumn, cool, copper,
gray, pink, and jet.
Note that while the color scale varies continuously, many states appear to
be the same color. This is because of the skewed distribution of state areas.
One way to differentiate the symbology is to clamp the lower end (because
the smallest patches, such as District of Columbia and Rhode Island, are
much smaller than average) and the upper end (because Alaskas area is so
much larger than that of any other state).
9 Change the colormap to one that has more hues and a smaller number of
steps, and redraw the colorbar to display the new value range:
minarea = 10000;
surfaceColors = makesymbolspec('Polygon',...
{'Default','FaceColor','red'}, ...
{'SurfaceArea', [ minarea maxarea], 'FaceColor', cool(16)});
geoshow(states,'DisplayType', 'polygon', ...
'SymbolSpec', surfaceColors)
6-22
Thematic Maps
caxis([minarea maxarea])
colormap(cool(16))
colorbar
Note how you can specify the size of a colormap with the colormap syntax
used above. Be aware that, because you clamped the value range, the
numeric limits of the colorbar overstate the minimum area and understate
the maximum area. However, the map gives much more information overall
because more states have distinct symbology, as the resulting map depicts.
Special Thematic Mapping Functions
In addition to choropleth maps, other Mapping Toolbox display and symbology
functions include
Function
Used For
cometm
Traces (animates) vectors slowly from a comet head
comet3m
Traces (animates) vectors in 3-D slowly from a comet
head
6-23
Customizing and Printing Maps
Function
Used For
quiverm
Plots directed vectors in 2-D from specified latitudes
and longitudes with lengths also specified as latitudes
and longitudes
quiver3m
Plots directed vectors in 3-D from specified latitudes,
longitudes, and altitudes with lengths also specified as
latitudes and longitudes and altitudes
scatterm
Draws fixed or proportional symbol maps for each point
in a vector with specified marker symbol. Similar maps
can be generated using geoshow and mapshow using
appropriate symbol specifications (symbolspecs).
stem3m
Projects a 3-D stem plot map on the current map axes
The cometm and quiverm functions operate like their MATLAB counterparts
comet and quiver. The stem3m function allows you to display geographic bar
graphs. Like the MATLAB scatter function, the scatterm function allows
you to display a thematic map with proportionally sized symbols. The tissot
function calculates and displays Tissot Indicatrices, which graphically portray
the shape distortions of any map projection. For more information on these
capabilities, consult the descriptions of these functions in the reference pages.
Stem Maps
Stem plots are 3-D geographic bar graphs portraying numeric attributes at
point locations, usually on vector base maps. Below is an example of a stem
plot over a map of the continental United States. The bars could represent
anything from selected city populations to the number of units of a product
purchased at each location:
6-24
Thematic Maps
Contour Maps
Contour and quiver plots can be useful in analyzing matrix data. In
the following example, contour elevation lines have been drawn over a
topographical map. The region displayed is the Gulf of Mexico, obtained from
the topo matrix. Quiver plots have been added to visualize the gradient of the
topographical matrix.
Here is the displayed map:
6-25
Customizing and Printing Maps
Scatter Maps
The scatterm function plots symbols at specified point locations, like the
MATLAB scatter function. If the symbols are small and inconspicuous and
do not vary in size, the result is a dot-distribution map. If the symbols vary
in size and/or shape according to a vector of attribute values, the result is
a proportional symbol map.
Below is an example of using scatterm to create a star chart of the northern
sky. The stars are represented by filled circles whose size is negatively
proportional to visual magnitude, because the brighter a star is, the smaller
its magnitude. (The very brightest stars actually have negative magnitude
values.) To execute the following commands, select them all by dragging over
the list in the Help browser, then right-click and choose Evaluate Selection.
% View the sky orthographically
axesm('MapProjection','ortho','MapLatLimit',[0 90])
gridm on
setm(gca,'LabelFormat','compass','LabelRotation','on')
setm(gca,'MLabelParallel',0,'PLabelMeridian',0)
setm(gca,'MeridianLabel','on','ParallelLabel','on')
setm(gca,'GlineStyle','-')
% For each star, use a symbol with area negatively
% proportional to the star's visual magnitude.
load stars
symbolArea = (20 - 2*vmag);
% Plot each star as a blue-filled circle.
h = scatterm(lat,long,symbolArea,'b','filled');
6-26
Thematic Maps
6-27
Customizing and Printing Maps
Using Cartesian MATLAB Display Functions
In this section...
Adding Graphic Objects to Map Axes on page 6-28
Example 1: Triangulating Data Points on page 6-28
Example 2: Constructing Quiver Maps on page 6-30
Adding Graphic Objects to Map Axes
If you cannot find a Mapping Toolbox display function that makes the kind of
display that you need, you might be able to use MATLAB functions. When
placing graphic objects on a map axes, you can use the MATLAB function to
add the graphic objects to the display, using latitude and longitude as x and y,
and then project the data afterwards.
Note Before applying MATLAB functions to geodata, you should take into
consideration that performing Cartesian geometric operations on geographic
coordinates can yield inaccurate results when the data covers large regions of
a planet or lies near one of its poles.
Example 1: Triangulating Data Points
There is no Mapping Toolbox function that displays a triangulated surface
from random data points, a structure generally known as a triangulated
irregular network (TIN). However, MATLAB does have a function to create
Delaunay triangles, a method that is often used to form TINs from projected
point coordinate data. Explore triangulating some point data and bringing
the result into a Mapping Toolbox map axes:
1 Use the seamount data provided as MATLAB demo data:
load seamount
2 Determine the bounds of the coordinates and add a degree of white space:
latlim = [min(y)-.5 max(y)+.5];
lonlim = [min(x)-.5 max(x)+.5];
6-28
Using Cartesian MATLAB Display Functions
3 Create map axes to contain the seamount region (worldmap selects a
projection for you):
worldmap(latlim,lonlim)
4 Create a Delaunay triangulation of x and y (longitude and latitude):
tri = delaunay(y,x);
5 Generate a 3-D surface that combines the triangulation and z-values:
h = trisurf(tri,y,x,z);
6 Map the surface onto the axes by projecting to the x-y plane (project is a
Mapping Toolbox function especially for this purpose):
project(h,'yx')
Note that even though the triangulated surface appears on the map, it does
not have a geostruct (see Mapping Toolbox Geographic Data Structures
on page 2-16).
7 Add a default graphic scale to the display:
scaleruler on
6-29
Customizing and Printing Maps
If, as in this example, the displayed objects are already in the right place and
do not need to be projected, you can trim them to the map frame and convert
them to mapped objects using trimcart and makemapped. They can then be
manipulated as if they had been created with map display functions.
Example 2: Constructing Quiver Maps
As was briefly described for text objects in Projected and Unprojected
Graphic Objects on page 4-37, you can also combine Mapping Toolbox and
MATLAB functions to mix spherical and Cartesian coordinates. An example
would be a quiver plot (sometimes known as a vector field) in which the
locations of the vectors are geographic, but the lengths, being specified by
attributes, are not. In that case, you can use Mapping Toolbox map projection
calculations and MATLAB graphics functions. Cylindrical projections are the
6-30
Using Cartesian MATLAB Display Functions
simplest to use because north is up, south is down, and east and west are
on an orthogonal axis.
In this example, you will impose a quiver map of the slope of a surface on
a world map. The surface is a Gaussian field generated by the MATLAB
peaks function.
figure; axesm mercator; framem; gridm
load coast
plotm(lat,long,'color',[.75 .75 .75])
[u,v] = gradient(peaks(13)/10);
[mlat,mlon] = meshgrat(-90:15:90,-180:30:180);
[x,y] = mfwdtran(mlat,mlon);
h = quiver(x,y,u,v,.2,'r');
trimcart(h)
tightmap
6-31
Customizing and Printing Maps
An extra step might be required for noncylindrical projections. In these
projections, compass directions vary with location. To make the directions
agree with the map grid, vectors should be rotated to bring them into
alignment. This can be done with the vector transformation function
vfwdtran. Consider the same data displayed on a conic projection.
load coast; figure
axesm('lambert','MapLatLimit',[-20 80])
framem; gridm
plotm(lat,long,'color',[.75 .75 .75])
[u,v] = gradient(peaks(13)/10);
[mlat,mlon] = meshgrat(-90:15:90,-180:30:180);
[x,y] = mfwdtran(mlat,mlon);
thproj = degtorad(vfwdtran(mlat,mlon,90*ones(size(mlat))));
[th,r] = cart2pol(u,v);
[uproj,vproj] = pol2cart(th+thproj,r);
h = quiver(x,y,uproj,vproj,0,'r') ;
trimcart(h)
tightmap
6-32
Using Cartesian MATLAB Display Functions
Conformal projections, such as this Lambert conformal conic, are often the
best choice for quiver displays. They preserve angles, ensuring that the
difference between north and east will always be 90 degrees in projected
coordinates.
6-33
Customizing and Printing Maps
Using Colormaps and Colorbars
In this section...
Colormap for Terrain Data on page 6-34
Contour Colormaps on page 6-37
Colormaps for Political Maps on page 6-39
Labeling Colorbars on page 6-43
Editing Colorbars on page 6-44
Colormap for Terrain Data
Colors and colorscales (ordered progressions of colors) are invaluable for
representing geographic variables on maps, particularly when you create
terrain and thematic maps. The following sections describe techniques and
provide examples for applying colormaps and colorbars to maps.
In previous examples, the function demcmap was used to color several digital
elevation model (DEM) topographic displays. This function creates colormaps
appropriate to rendering DEMs, although it is certainly not limited to DEMs.
These colormaps, by default, have atlas-like colors varying with elevation or
depth that properly preserve the land-sea interface. In cartography, such
color schemes are called hypsometric tints.
1 Here you explore demcmap using the topographic data for the Korean
peninsula provided in the korea data set. To set up an appropriate map
projection, pass the korea data grid and referencing vector to worldmap:
load korea
figure
worldmap(map,refvec)
2 Display the data grid with geoshow:
geoshow(map, refvec, 'DisplayType', 'mesh')
6-34
Using Colormaps and Colorbars
3 The Korea DEM is displayed using the default colormap, which is
inappropriate and causes the surface to be unrecognizable. Now apply
the default DEM colormap:
demcmap(map)
6-35
Customizing and Printing Maps
4 You can also make demcmap assign all altitudes within a particular range
to the same color. This results in a quasi-contour map with breaks at
a constant interval. Now color this map using the same color scheme
coarsened to display 500 meter bands:
demcmap('inc',map,500)
colorbar
Note that the first argument to demcmap, 'inc', indicates that the third
argument should be interpreted as a value range. If you prefer, you can
specify the desired number of colors with the third argument by setting the
first argument to 'size'.
6-36
Using Colormaps and Colorbars
Contour Colormaps
You can create colormaps that make surfaces look like contour maps for other
types of data besides terrain. The contourcmap function creates a colormap
that has color changes at a fixed value increment. Its required arguments are
the increment value and the name of a colormap function. Optionally, you can
also use contourcmap to add and label a colorbar similarly to the MATLAB
colorbar function:
1 Explore contourcmap by loading the world geoid data set and rendering
it with a default colormap:
load geoid
figure;
worldmap(geoid,geoidrefvec)
6-37
Customizing and Printing Maps
geoshow(geoid, geoidrefvec, 'DisplayType', 'surface')
2 Use contourcmap to specify a contour interval of 10 (meters), and to place a
colorbar beneath the map:
contourcmap(10,'jet','colorbar','on','location','horizontal')
3 If you want to render a restricted value range, you can enter a vector of
evenly spaced values for the first argument. Here you specify a 5-meter
interval and truncate symbology at 0 meters on the low end and 50 meters
at the high end:
contourcmap([0:5:50],...
'jet','colorbar','on','location','horizontal')
6-38
Using Colormaps and Colorbars
Should you need to write a custom colormap function, for example, one that
has irregular contour intervals, you can easily do so, but it should have the
N-by-3 structure of MATLAB colormaps.
Colormaps for Political Maps
Political maps typically use muted, contrasting colors that make it easy to
distinguish one country from its neighbors. You can create colormaps of this
kind using the polcmap function. The polcmap function creates a colormap
with randomly selected colors of all hues. Since the colors are random, if you
dont like the result, execute polcmap again to generate a different colormap:
1 To explore political colormaps, display the usastatelo data set as patches,
setting up the map with worldmap and plotting it with geoshow:
figure
worldmap na
6-39
Customizing and Printing Maps
states = shaperead('usastatelo', 'UseGeoCoords', true);
geoshow(states)
Note that the default face color is black, which is not very interesting.
2 Use polcmap to populate color definitions to a symbolspec to randomly
recolor the patches and expand the map to fill the frame:
faceColors = makesymbolspec('Polygon',...
{'INDEX', [1 numel(states)], 'FaceColor',...
polcmap(numel(states))});
geoshow(states,'SymbolSpec',faceColors)
6-40
Using Colormaps and Colorbars
3 The polcmap function can also control the number and saturation of colors.
Reissue the command specifying 256 colors and a maximum saturation of
0.2. To ensure that the colormap is always the same, reset the seed on the
MATLAB random number function using the 'state' argument with a
fixed value of your choice:
figure
worldmap na
rand('state',0)
faceColors = makesymbolspec('Polygon',...
{'INDEX', [1 numel(states)], 'FaceColor', polcmap(256,.2)});
geoshow(states, 'SymbolSpec', faceColors)
6-41
Customizing and Printing Maps
4 For maximum control over the colors, specify the ranges of hues,
saturations, and values. Use the same set of random color indices as before.
figure
worldmap na
rand('state',0)
faceColors = makesymbolspec('Polygon', ...
{'INDEX', [1 numel(states)], ...
'FaceColor', polcmap(256,[.2 .5],[.3 .3],[1 1]) });
geoshow(states, 'SymbolSpec', faceColors)
6-42
Using Colormaps and Colorbars
Note The famous Four Color theorem states that any political map can be
colored to completely differentiate neighboring patches using only four colors.
Experiment to find how many colors it takes to color neighbors differently
with polcmap.
Labeling Colorbars
Political maps are an example of nominal data display. Many nominal data
sets have names associated with a set of integer values, or consist of codes
that identify values that are ordinal in nature (such as low, medium, and
high). The function lcolorbar creates a colorbar having a text label aligned
with each color. Nominal colorbars are customarily used only with small
colormaps (where 10 categories or fewer are being displayed). lcolorbar has
options for orienting the colorbar and aligning text in addition to the graphic
properties it shares with axes objects.
figure; colormap(jet(5))
labels = {'apples','oranges','grapes','peaches','melons'};
lcolorbar(labels,'fontweight','bold');
6-43
Customizing and Printing Maps
Editing Colorbars
Maps of nominal data often require colormaps with special colors for each
index value. To avoid building such colormaps by hand, use the MATLAB
GUI for colormaps, colormapeditor, described in the MATLAB Function
Reference pages. Also see the MATLAB colormap function documentation.
6-44
Printing Maps to Scale
Printing Maps to Scale
Maps are often printed at a size that makes objects on paper a particular
fraction of their real size. The linear ratio of the mapped to real object sizes
is called map scale, and it is usually notated with a colon as 1:1,000,000 or
1:24,000. Another way of specifying scale is to call out the printed and real
lengths, for example 1 inch = 1 mile.
You can specify the printed scale using the paperscale function. It modifies
the size of the printed area on the page to match the scale. If the resulting
dimensions are larger than your paper, you can reduce the amount of empty
space around the map using tightmap, zoom, or panzoom, and by changing
the axes position to fill the figure. This also reduces the amount of memory
needed to print with the zbuffer (raster image) renderer. Be sure to set
the paper scale last. For example,
set(gca,'Units','Normalized','Position',[0 0 1 1])
tightmap
paperscale(1,'in', 5,'miles')
The paperscale function also can take a scale denominator as its first and
only argument. If you want the map to be printed at 1:20,000,000, type
paperscale(2e7)
To check the size and extent of text and the relative position of axes, use
previewmap, which resizes the figure to the printed size.
previewmap
For more information on printing, see the Printing and Exporting section of
the MATLAB Graphics documentation.
6-45
6-46
Customizing and Printing Maps
7
Manipulating Geospatial
Data
For some purposes, geospatial data is fine to use as is. Sooner or later,
though, you need to extract, combine, massage, and transform geodata. This
chapter discusses some Mapping Toolbox tools and techniques provided for
such purposes.
Manipulating Vector Geodata on page 7-2
Manipulating Raster Geodata on page 7-32
Manipulating Geospatial Data
Manipulating Vector Geodata
In this section...
Repackaging Vector Objects on page 7-2
Matching Line Segments on page 7-4
Geographic Interpolation of Vectors on page 7-5
Vector Intersections on page 7-8
Polygon Area on page 7-11
Overlaying Polygons with Set Logic on page 7-12
Cutting Polygons at the Date Line on page 7-17
Building Buffer Zones on page 7-19
Trimming Vector Data to a Rectangular Region on page 7-22
Trimming Vector Data to an Arbitrary Region on page 7-25
Simplifying Vector Coordinate Data on page 7-25
Repackaging Vector Objects
It can be difficult to identify line or patch segments once they have been
combined into large NaN-clipped vectors. You can separate these polygon or
line vectors into their component segments using polysplit, which takes
column vectors as inputs.
Extracting and Joining Polygons or Line Segments
1 Enter two NaN-delimited arrays in the form of column vectors:
lat = [45.6 -23.47 78 NaN 43.9 -67.14 90 -89]';
long = [13 -97.45 165 NaN 0 -114.2 -18 0]';
2 Use polysplit to create two cell arrays, latc and lonc:
[latc,lonc] = polysplit(lat,long)
latc =
7-2
Manipulating Vector Geodata
[3x1 double]
lonc =
[3x1 double]
[4x1 double]
[4x1 double]
3 Inspect the contents of the cell arrays:
[latc{1} lonc{1}]
[latc{2} lonc{2}]
ans =
45.6
-23.47
78
13
-97.45
165
43.9
-67.14
90
-89
0
-114.2
-18
0
ans =
Note that each cell array element contains a segment of the original line.
4 To reverse the process, use polyjoin:
[lat2,lon2] = polyjoin(latc,lonc);
5 The joined segments are identical with the initial lat and lon arrays:
[lat long] == [lat2 lon2]
ans =
1
1
1
0
1
1
1
1
1
1
1
0
1
1
1
1
The logical comparison is false for the NaN delimiters, by definition.
7-3
Manipulating Geospatial Data
6 You can test for global equality, including NaNs, as follows:
isequalwithequalnans(lat,lat2) & isequalwithequalnans(long,lon2)
ans =
1
See the polysplit and polyjoin reference pages for further information.
Matching Line Segments
A common operation on sets of line segments is the concatenation of segments
that have matching endpoints. The polymerge command compares endpoints
of segments within latitude and longitude vectors to identify endpoints that
match exactly or lie within a specified distance. The matching segments are
then concatenated, and the process continues until no more coincidental
endpoints can be found. The two required arguments are a latitude (x) vector
and a longitude (y) vector. The following exercise shows this process at work.
Linking Line Segments into Polygons
1 Construct column vectors representing coordinate values:
lat = [3 2 NaN 1 2 NaN 5 6 NaN 3 4]';
lon = [13 12 NaN 11 12 NaN 15 16 NaN 13 14]';
2 Concatenate the segments that match exactly:
[latm,lonm] = polymerge(lat,lon);
[latm lonm]
ans =
1
2
3
4
NaN
5
6
7-4
11
12
13
14
NaN
15
16
Manipulating Vector Geodata
NaN
NaN
The original four segments are merged into two segments.
The polymerge function takes an optional third argument, a (circular)
distance tolerance that permits inexact matching. A fourth argument enables
you to specify whether the function outputs vectors or cell arrays. See the
polymerge reference page for further information.
Geographic Interpolation of Vectors
When using vector data, remember that, like raster data, coordinates are
sampled measurements. This involves unavoidable assumptions concerning
what the geographic reality is between specified data points. The normal
assumption when plotting vector data requires that points be connected
with straight line segments, which essentially indicates a lack of knowledge
about conditions between the measured points. For lines that are by nature
continuous, such as most rivers and coastlines, such piecewise linear
interpolation can be false and misleading, as the following figure depicts.
Interpolating between sparse data points can mislead
Stream channel
Digitized channel
Interpolated
points
Interpolating Sparse Vector Data
Despite the possibility of misinterpretation, circumstances do exist in which
geographic data interpolation is useful or even necessary. To do this, use the
interpm function to interpolate between known data points. One value of
linearly interpolating points is to fill in lines of constant latitude or longitude
(e.g., administrative boundaries) that can curve when projected.
7-5
Manipulating Geospatial Data
Interpolating Vectors to Achieve a Minimum Point Density
This example interpolates values in a set of latitude and longitude points to
have no more than one degree of separation in either direction.
1 Define two fictitious latitude and longitude data vectors:
lats = [1 2 4 5]; longs = [1 3 4 5];
2 Specify a densification parameter of 1 (the default unit is degrees):
maxdiff = 1;
3 Call interpm to fill in any gaps greater than 1 in either direction:
[newlats,newlongs] = interpm(lats,longs,maxdiff)
newlats =
1.0000
1.5000
2.0000
3.0000
4.0000
5.0000
newlongs =
1.0000
2.0000
3.0000
3.5000
4.0000
5.0000
In lats, a gap of 2 exists between the values 2 and 4. A linearly
interpolated point, (3,3.5) was therefore inserted in newlats and
newlongs. Similarly, in longs, a gap of 2 exists between the 1 and the 3.
The point (1.5, 2) was therefore interpolated and placed into newlats
and newlongs. Now, the separation of adjacent points is no greater than
maxdiff in either newlats or newlongs.
See the interpm reference page for further information.
7-6
Manipulating Vector Geodata
Interpolating Coordinates at Specific Locations
interpm returns both the original data and new linearly interpolated points.
Sometimes, however, you might want only the interpolated values. The
functions intrplat and intrplon work similarly to the MATLAB interp1
function, and give you control over the method used for interpolation. Note
that they only interpolate and return one value at a time.
Use intrplat to interpolate a latitude for a given longitude. Given a
monotonic set of longitudes and their matching latitude points, you can
interpolate a new latitude for a longitude you specify, interpolating along
linear, spline, cubic, rhumb line, or great circle paths. The longitudes must
increase or decrease monotonically. If this is not the case, you might be able
to use the intrplon companion function if the latitude values are monotonic.
Interpolate a latitude corresponding to a longitude of 7.3 in the following
data in a linear, great circle, and rhumb line sense:
1 Define some fictitious latitudes and longitudes:
longs = [1 3 4 9 13]; lats = [57 68 60 65 56];
2 Specify the longitude for which to compute a latitude:
newlong = 7.3;
3 Generate a new latitude with linear interpolation:
newlat = intrplat(longs,lats,newlong,'linear')
newlat =
63.3000
4 Generate the latitude using great circle interpolation:
newlat = intrplat(longs,lats,newlong,'gc')
newlat =
63.5029
5 Generate it again, specifying interpolation along a rhumb line:
7-7
Manipulating Geospatial Data
newlat = intrplat(longs,lats,newlong,'rh')
newlat =
63.3937
The following diagram illustrates these three types of interpolation. The
intrplat function also can perform spline and cubic spline interpolations.
(65, 9)
Rhumb line latitude = 63.5029
Great circle latitude = 63.3937
Linear latitude = 63.3000
(60, 4)
(Longitude = 7.3)
As mentioned above, the intrplon function provides the capability to
interpolate new longitudes from a given set of longitudes and monotonic
latitudes.
See the intrplat and intrplon reference pages for further information.
Vector Intersections
A set of Mapping Toolbox functions perform intersection calculations on
vector data computed by the toolbox, which include great and small circles
as well as rhumb line tracks. The functions also determine intersections of
arbitrary vector data.
Compute the intersection of a small circle centered at (0,0) with a radius of
1250 nautical miles and a small circle centered at (5N,30E) with a radius of
2500 kilometers:
[lat,long] = scxsc(0,0,nm2deg(1250),5,30,km2deg(2500))
7-8
Manipulating Vector Geodata
lat =
17.7487 -12.9839
long =
11.0624 16.4170
(17.7N, 11.1E)
(5N, 30E)
2500 km
1250 nm
(0, 0)
(13.0N, 16.4E)
In general, small circles intersect twice or never. For the case of exact
tangency, scxsc returns two identical intersection points. Other similar
commands include rhxrh for intersecting rhumb lines, gcxgc for intersecting
great circles, and gcxsc for intersecting a great circle with a small circle.
Imagine a ship setting sail from Norfolk, Virginia (37N,76W), maintaining
a steady due-east course (90), and another ship setting sail from Dakar,
Senegal (15N,17W), with a steady northwest course (315). Where would
the tracks of the two vessels cross?
[lat,long] = rhxrh(37,-76,90,15,-17,315)
lat =
37
7-9
Manipulating Geospatial Data
long =
-41.7028
The intersection of the tracks is at (37N,41.7W), which is roughly 600
nautical miles west of the Azores in the Atlantic Ocean.
You can also compute the intersection points of arbitrary vectors of latitude
and longitude. The polyxpoly command finds the segments that intersect
and interpolates to find the intersection points. The interpolation is done
linearly, as if the points were in a Cartesian x-y coordinate system. The
polyxpoly command can also identify the line segment numbers associated
with the intersections:
[xint,yint] = polyxpoly(x1,y1,x2,y2);
7-10
Manipulating Vector Geodata
If the spacing between points is large, there can be some difference between
the intersection points computed by polyxpoly and the intersections shown
on a map display. This is a result of the difference between straight lines in
the unprojected and projected coordinates. Similarly, there can be differences
between the polyxpoly result and intersections assuming great circles or
rhumb lines between points.
Polygon Area
Use the function areaint to calculate geographic areas for vector data in
polygon format. The function performs a numerical integration using Greens
Theorem for the area on a surface enclosed by a polygon. Because this is a
discrete integration on discrete data, the results are not exact. Nevertheless,
the method provides the best means of calculating the areas of arbitrarily
shaped regions. Better measures result from better data.
The Mapping Toolbox function areaint (for area by integration), like the
other area functions, areaquad and areamat, returns areas as a fraction of
the entire planets surface, unless a radius is provided. Here you calculate
the area of the continental United States using the conus MAT-file. Three
areas are returned, because the data contains three polygons: Long Island,
Marthas Vineyard, and the rest of the continental U.S.:
load conus
earthradius = almanac('earth','radius');
7-11
Manipulating Geospatial Data
area = areaint(uslat,uslon,earthradius)
area =
1.0e+06 *
7.9256
0.0035
0.0004
Because the default Earth radius is in kilometers, the area is in square
kilometers. From the same variables, the areas of the Great Lakes can be
calculated, this time in square miles:
load conus
earthradius = almanac('earth','radius','miles');
area = areaint(gtlakelat,gtlakelon,earthradius)
area =
1.0e+004 *
8.0119
1.0381
0.7634
Again, three areas are returned, the largest for the polygon representing
Superior, Michigan, and Huron together, the other two for Erie and Ontario.
Overlaying Polygons with Set Logic
Polygon set operations are used to answer a variety of questions about logical
relationships of vector data polygon objects. Standard set operations include
intersection, union, subtraction, and an exclusive OR operation. The polybool
function performs these operations on two sets of vectors, which can represent
x-y or latitude-longitude coordinate pairs. In computing points where
boundaries intersect, interpolations are carried out on the coordinates as if
they were planar. Here is an example that shows all the available operations.
7-12
Manipulating Vector Geodata
Intersection
Union
Exclusive Or
Subtraction
The result is returned as NaN-clipped vectors by default. In cases where it
is important to distinguish outer contours of polygons from interior holes,
polybool can also accept inputs and return outputs as cell arrays. In the
cell array format, a cell array entry starts with the list of points making up
the outer contour. Subsequent NaN-clipped faces within the cell entry are
interpreted as interior holes.
Overlaying Polygons with the polybool Function
The following exercise demonstrates how you can use polybool:
1 Construct a twelve-sided polygon:
7-13
Manipulating Geospatial Data
theta = -(0:pi/6:2*pi)';
lat1 = sin(theta);
lon1 = cos(theta);
2 Construct a triangle that overlaps it:
lat2 = [0 1 -1 0]';
lon2 = [0 2 2 0]';
3 Plot the two shapes together with blue and red lines:
axesm miller
plotm(lat1,lon1,'b')
plotm(lat2,lon2,'r')
4 Compute the intersection polygon and plot it as a green patch:
[loni,lati] = polybool('intersection',lon1,lat1,lon2,lat2);
[lati loni]
geoshow(lati,loni,'DisplayType','polygon','FaceColor','g')
ans =
0
-0.4409
0
0.4409
0
1.0000
0.8819
0
0.8819
1.0000
5 Compute the union polygon and plot it as a magenta patch:
[lonu,latu] = polybool('union',lon1,lat1,lon2,lat2);
[latu lonu]
geoshow(latu,lonu,'DisplayType','polygon','FaceColor','m')
ans =
-1.0000
-0.4409
-0.5000
-0.8660
-1.0000
-0.8660
7-14
2.0000
0.8819
0.8660
0.5000
0.0000
-0.5000
Manipulating Vector Geodata
-0.5000
0
0.5000
0.8660
1.0000
0.8660
0.5000
0.4409
1.0000
-1.0000
-0.8660
-1.0000
-0.8660
-0.5000
-0.0000
0.5000
0.8660
0.8819
2.0000
2.0000
6 Compute the exclusive OR polygon and plot it as a yellow patch:
[lonx,latx] = polybool('xor',lon1,lat1,lon2,lat2);
[latx lonx]
geoshow(latx,lonx,'DisplayType','polygon','FaceColor','y')
ans =
-1.0000
-0.4409
-0.5000
-0.8660
-1.0000
-0.8660
-0.5000
0
0.5000
0.8660
1.0000
0.8660
0.5000
0.4409
1.0000
-1.0000
NaN
0.4409
0
-0.4409
0
0.4409
2.0000
0.8819
0.8660
0.5000
0.0000
-0.5000
-0.8660
-1.0000
-0.8660
-0.5000
-0.0000
0.5000
0.8660
0.8819
2.0000
2.0000
NaN
0.8819
0
0.8819
1.0000
0.8819
7-15
Manipulating Geospatial Data
7 Subtract the triangle from the 12-sided polygon and plot the resulting
concave polygon as a white patch:
[lonm,latm] = polybool('minus',lon1,lat1,lon2,lat2);
[latm lonm]
geoshow(latm,lonm,'DisplayType','polygon','FaceColor','w')
ans =
0.8660
0.5000
0.4409
0
-0.4409
-0.5000
-0.8660
-1.0000
-0.8660
-0.5000
0
0.5000
0.8660
1.0000
0.8660
0.5000
0.8660
0.8819
0
0.8819
0.8660
0.5000
0.0000
-0.5000
-0.8660
-1.0000
-0.8660
-0.5000
-0.0000
0.5000
The final set of colored shapes is shown below.
7-16
Manipulating Vector Geodata
See the polybool reference page for further information.
Cutting Polygons at the Date Line
Polygon set operations treat input vectors as plane coordinates. The
polyxpoly function can be confused by geographic data that has
discontinuities in longitude coordinates at date-line crossings. This can
happen when points with longitudes near 180 connect to points with
longitudes near -180, as might be the case for eastern Siberia and Antarctica,
and also for small circles and other patch objects generated by toolbox
functions.
You can prepare such geographic data for use with polybool or for patch
rendering by cutting the polygons at the date line with the flatearthpoly
function. The result of flatearthpoly is a polygon with points inserted to
follow the date line up to the pole, traverse the longitudes at the pole, and
return to the date line crossing along the other edge of the date line.
Removing Discontinuities from a Small Circle
1 Create an orthographic view of the Earth and plot coast on it:
axesm ortho
setm(gca,'Origin', [60 170]); framem on; gridm on
7-17
Manipulating Geospatial Data
load coast
plotm(lat, long)
2 Generate a small circle that encompasses the North Pole and color it yellow:
[latc,lonc] = scircle1(75,45,30);
patchm(latc,lonc,'y')
3 Flatten the small circle with flatearthpoly:
[latf,lonf] = flatearthpoly(latc,lonc);
4 Plot the cut circle that you just generated as a magenta line:
plotm(latf,lonf,'m')
5 Generate a second small circle that does not include a pole:
[latc1 lonc1] = scircle1(20, 170, 30);
6 Flatten it and plot it as a red line:
[latf1,lonf1] = flatearthpoly(latc1,lonc1);
plotm(latf1,lonf1,'r')
The following figure shows the result of these operations. Note that the
second small circle, which does not cover a pole, has been clipped into two
pieces along the date line. On the right, the polygon for the first small circle
is plotted in plane coordinates to illustrate its flattened shape.
7-18
Manipulating Vector Geodata
The flatearthpoly function assumes that the interior of the polygon being
flattened is in the hemisphere that contains most of its edge points. Thus a
polygon produced by flatearthpoly does not cover more than a hemisphere.
Note As this figure illustrates, you do not need to use flatearthpoly to
prepare data for a map display. The Mapping Toolbox display functions
automatically cut and trim geographic data if required by the map projection.
Use this function only when conducting set operations on polygons.
See the flatearthpoly reference page for further information.
Building Buffer Zones
A buffer zone is the area within a specified distance of a map feature. For
vector geodata, buffer zones are constructed as polygons. For raster geodata,
buffer zones are collections of contiguous, identically coded grid cells. When
the feature is a polygon, a buffer zone can be defined as the locus of points
within a certain distance of its boundary, either inside or outside the polygon.
A buffer zone for a linear object is the locus of points a certain distance away
from it. Buffer zones form equidistant contour lines around objects.
7-19
Manipulating Geospatial Data
The bufferm function computes and returns vectors that represent a set of
points that define a buffer zone. It forms the buffer by placing small circles at
the vertices of the polygon and rectangles along each of its line segments, and
applying the union set operation to these objects.
Generating a Buffer Around a Compound Polygon
Demonstrate bufferm using a compound polygon representing the Island of
Madagascar that you extract from the landareas data set. The boundary
of Madagascar is passed to bufferm as NaN-clipped latitude and longitude
vectors. Using this data, compute a buffer zone at a distance of 0.75 degrees
out from the boundaries of Madagascar:
1 Create a base map of the area surrounding Madagascar, and hide the
border:
ax = worldmap('madagascar');
madagascar = shaperead('landareas',...
'UseGeoCoords', true,...
'Selector', {@(name)strcmpi(name,'Madagascar'), 'Name'});
geoshow(ax, madagascar, 'FaceColor', 'none');
madaLat = madagascar.Lat;
madaLon = madagascar.Lon;
7-20
Manipulating Vector Geodata
2 Use bufferm to process the polygon and output a buffer zone .75 degrees
inland:
[latb,lonb] = bufferm(madaLat, madaLon, .75, 'in');
This can take several minutes, because of the great number of geometric
computations that bufferm is performing.
3 Show the buffer zone in yellow, and the rest of the region in green. This is
achieved by drawing Madagascar in yellow and the buffer zone in green:
patchesm(madaLat, madaLon, 'y')
patchesm(latb, lonb, 'g')
7-21
Manipulating Geospatial Data
Trimming Vector Data to a Rectangular Region
It is not unusual for vector data to extend beyond the geographic region
currently of interest. For example, you might have coastline data for the
entire world (such as the coast data set), but are interested in mapping
Australia only. In this and other situations, you might want to eliminate
unnecessary data from the workspace and from calculations in order to save
memory or to speed up processing and display.
Line data and patch data need to be trimmed differently. You can trim line
data by simply removing points outside the region of interest by clipping lines
at the map frame or to some other defined region. Patch data requires a more
complicated method to ensure that the patch objects are correctly formed.
For the vector data, two functions are available to achieve this. If the vectors
are to be handled as line data, the maptriml function returns variables
containing only those points that lie within the defined region. If, instead,
you want to maintain polygon format, use the maptrimp function. Be aware,
however, that patch-trimmed data is usually larger and more expensive to
compute.
7-22
Manipulating Vector Geodata
Note When drawing maps, Mapping Toolbox display functions automatically
trim vector geodata to the region specified by the frame limits (FLatLimit and
FLonLimit map axes properties) for azimuthal projections, or to frame or map
limits (MapLatLimit and MapLonLimit map axes properties) for nonazimuthal
projections. The trimming is done internally in the display routine, keeping
the original data intact. For further information on trimming vector geodata,
see Axes for Drawing Maps on page 4-12, along with the reference pages
for the trimming functions.
Trimming Vectors to Form Lines and Polygons
1 Load the coast MAT-file for the entire world:
load coast
2 Define a region of interest centered on Australia:
latlim = [-50 0]; longlim = [105 160];
3 Use maptriml to delete all data outside these limits, producing line vectors:
[linelat,linelong] = maptriml(lat,long,latlim,longlim);
4 Do this again, but use maptrimp to produce polygon vectors:
[polylat,polylong] = maptrimp(lat,long,latlim,longlim);
5 See how much data has been reduced:
whos
Name
lat
latlim
linelat
linelong
long
Size
9589x1
1x2
870x1
870x1
9589x1
Bytes
Class
76712
16
6960
6960
76712
double
double
double
double
double
7-23
Manipulating Geospatial Data
longlim
polylat
polylong
1x2
878x1
878x1
16
7024
7024
double
double
double
Note that the clipped data is only 10% as large as the original data set.
6 Plot the trimmed patch vectors on a Miller projection:
axesm('MapProjection', 'miller', 'Frame', 'on',...
'FlatLimit', latlim, 'FlonLimit', longlim)
patchesm(polylat, polylong, 'c')
7 Plot the trimmed line vectors to see that they conform to the patches:
plotm(linelat, linelong, 'm')
See the maptriml and maptrimp reference pages for further information.
7-24
Manipulating Vector Geodata
Trimming Vector Data to an Arbitrary Region
Often a set of data contains unwanted data mixed in with the desired values.
For example, your data might include vectors covering the entire United
States, but you only want to work with those falling in Alabama. Sometimes a
data set contains noiseperhaps three or four points out of several thousand
are obvious errors (for example, one of your city points is in the middle of the
ocean). In such cases, locating outliers and errors in the data arrays can
be quite tedious.
The filterm command uses a data grid to filter a vector data set. Its calling
sequence is as follows:
[flats,flons] = filterm(lats,lons,grid,refvector,allowed)
Each location defined by lats and lons is mapped to a cell in grid, and the
value of that grid cell is obtained. If that value is found in allowed, that point
is output to flats and flons. Otherwise, the point is filtered out.
The grid might encode political units, and the allowed values might be the
code or codes indexing certain states or countries (e.g., Alabama). The grid
might also be real-valued (e.g., terrain elevations), although it could be
awkward to specify all the values allowed. More often, logical or relational
operators give better results for such grids, enabling the allowed value to be 1
(for true). For example, you could use this transformation of the topo grid:
[flats,flons] = filterm(lats,lons,double(topo>0),topolegend,1)
The output would be those points in lats and lons that occupy dry land
(mostly because some water bodies are above sea level).
For further information, see the filtermreference page. Also see Data Grids
as Logical Variables on page 7-40.
Simplifying Vector Coordinate Data
Avoiding visual clutter in composing maps is an essential part of cartographic
presentation. In cartography, this is described as map generalization,
which involves coordinating many techniques, both manual and automated.
Limiting the number of points in vector geodata is an important part of
generalizing maps, and is especially useful for conditioning cartographic
7-25
Manipulating Geospatial Data
data, plotting maps at small scales, and creating versions of geodata for use
at small scales.
An easy, but naive, approach to point reduction is to discard every nth
element in each coordinate vector (simple decimation). However, this can
result in poor representations of the original shapes. The toolbox provides a
function to eliminate insignificant geometric detail in linear and polygonal
objects, while still maintaining accurate representations of their shapes.
The reducem function implements a powerful line simplification algorithm
(known as Douglas-Peucker) that intelligently selects and deletes visually
redundant points.
The reducem function takes latitude and longitude vectors, plus an optional
linear tolerance parameter as arguments, and outputs reduced (simplified)
versions of the vectors, in which deviations perpendicular to local trend lines
in the vectors are all greater than the tolerance criterion. Endpoints of vectors
are preserved. Optional outputs are an error measure and the tolerance value
used (it is computed when you do not supply a value).
Note Simplified line data might not always be appropriate for display. If all
or most intermediate points in a feature are deleted, then lines that appear
straight in one projection can be incorrectly displayed as straight lines in
others, and separate lines can be caused to intersect. In addition, when you
are reducing data over large world regions, the effective degree of reduction
near the poles are less than that achieved near the equator, due to the fact
that the algorithm treats geographic coordinates as if they were planar.
Using reducem to Simplify Lines
The reducem function works on both patch and line data. Getting results that
look right at an intended scale might require some experimentation with the
tolerance parameter. The best way to proceed might be to allow the tolerance
to default, and have reducem return the tolerance it computed as the fourth
return argument. If the output still has too much detail, then double the
tolerance and try again. Similarly, if the output lines do not have enough
detail, halve the tolerance and try again. You can also use the third return
parameter, which indicates the percentage of line length that was eliminated
7-26
Manipulating Vector Geodata
by reduction, as a guide to achieve consistent simplification results, although
this parameter is sensitive to line geometry and thus can vary by feature type.
To demonstrate the use of reducem, this example extracts the outline of the
state of Massachusetts from the usastatehi high-resolution shapefile:
1 Read Massachusetts data from the shapefile. Use the Selector parameter
to read only the vectors representing the Massachusetts state boundaries:
ma = shaperead('usastatehi.shp',...
'UseGeoCoords', true,...
'Selector', {@(name)strcmpi(name,'Massachusetts'), 'Name'});
2 Extract the coordinate data for simplification. There are 957 points to
begin with:
maLat = ma.Lat;
maLon = ma.Lon;
numel(maLat)
ans =
957
3 Use reducem to simplify the boundary vectors, and inspect the results:
[maLat1, maLon1, cerr, tol] = reducem(maLat', maLon');
numel(maLat1)
ans =
252
4 The number of points used to represent the boundary has dropped from 958
to 253. Compute the degree of reduction:
numel(maLat1)/numel(maLat)
ans =
0.2633
7-27
Manipulating Geospatial Data
The vectors have been reduced to about a quarter of their original size
using the default tolerance.
5 Examine the error and tolerance values returned by reducem:
[cerr tol]
ans =
0.0331
0.0060
The cerr value says that only 3.3% of total boundary length was eliminated
(despite removing 74% of the points). The tolerance that achieved this was
computed by reducem as 0.006 decimal degrees, or about 0.66 km.
6 Use geoshow to plot the reduced outline in red over the original outline
in blue:
figure
axesm('MapProjection', 'eqdcyl', 'FlatLim', [41.1 43.0],...
'FlonLim', [-69.8, -73.6], 'Frame', 'off', 'Grid', 'off');
geoshow(maLat, maLon, 'DisplayType', 'line', 'color', 'blue')
geoshow(maLat1, maLon1, 'DisplayType', 'line', 'color', 'red')
Differences in details are not apparent unless you zoom in two or three
times; click the Zoom tool to explore the map.
7 Double the tolerance, and reduce the original boundary into new variables:
[maLat2,maLon2,cerr2,tol2] = reducem(maLat', maLon', 0.012);
8 Repeat step 3 with new data and plot it in dark green:
numel(maLat2)/numel(maLat)
ans =
0.1641
[cerr2 tol2]
7-28
Manipulating Vector Geodata
ans =
0.0517 0.0120
geoshow(maLat2, maLon2, 'DisplayType', 'line', 'color', [0 .6 0])
Now you have removed 84% of the points, and 5.2% of total length.
9 Repeat one more time, raising the tolerance to 0.1 degrees, and plot the
result in black:
[maLat3, maLon3, cerr3, tol3] = reducem(maLat', maLon', 0.1);
geoshow(maLat3, maLon3, 'DisplayType', 'line', 'color', 'black')
As overlaid with the original data, the reduced state boundaries look like
this.
7-29
Manipulating Geospatial Data
As this example and the composite map below demonstrate, the visual
effects of point reduction are subtle, up to a point. Most of the vertices can
be eliminated before the effects of line simplification are very noticeable.
Experimentation is usually required, because the visual effects a given value
for a tolerance yield depend on the degrees and types of line complexity, and
they are often nonlinear with respect to tolerance values. Also, the extent of
line detail reduction should be informed by the purpose of the map and the
scale at which it is to be displayed.
Note This exercise generalized a set of disconnected patches. When patches
are contiguous (such as the U.S. state outlines), using reducem can result in
inconsistencies in boundary representation and gaps at points where states
meet. For best results, reducem should be applied to line data.
7-30
Manipulating Vector Geodata
42.5 N
42.5 N
42.0 N
42.0 N
41.5 N
No reduction
957 points (100%)
73 W
72 W
71 W
41.5 N
70 W
73 W
42.5 N
42.5 N
42.0 N
42.0 N
41.5 N
Tol: 0.012 deg
157 points (16%)
73 W
72 W
71 W
41.5 N
70 W
Tol: 0.006 deg.
deg
252 points (26%)
72 W
71 W
70 W
71 W
70 W
Tol: 0.100 deg
32 points (3%)
73 W
72 W
See the reducem reference page for further information.
7-31
Manipulating Geospatial Data
Manipulating Raster Geodata
In this section...
Vector-to-Raster Data Conversion on page 7-32
Data Grids as Logical Variables on page 7-40
Data Grid Values Along a Path on page 7-42
Data Grid Gradient, Slope, and Aspect on page 7-44
Vector-to-Raster Data Conversion
You can convert latitude-longitude vector data to a grid at any resolution you
choose to make a raster base map or grid layer. Certain Mapping Toolbox
GUI tools help you do some of this, but you can also perform vector-to-raster
conversions from the command line. The principal function for gridding vector
data is vec2mtx, which allocates lines to a grid of any size you indicate,
marking the lines with 1s and the unoccupied grid cells with 0s. The grid
contains doubles, but if you want a logical grid (see Data Grids as Logical
Variables on page 7-40, below) cast the result to be a logical array.
If the vector data consists of polygons (patches), the gridded outlines are
all hollow. You can differentiate them using the encodem function, calling
it with an array of rows, columns, and seed values to produce a new grid
containing polygonal areas filled with the seed values to replace the binary
values generated by vec2mtx.
Creating Data Grids from Vector Data
To demonstrate vector-to-raster data conversion, use patch data for Indiana
from the usastatehi shapefile:
1 Use shaperead to get the patch data for the boundary:
indiana = shaperead('usastatehi.shp',...
'UseGeoCoords', true,...
'Selector', {@(name)strcmpi('Indiana',name), 'Name'});
inLat = indiana.Lat;
inLon = indiana.Lon;
7-32
Manipulating Raster Geodata
2 Set the grid density to be 40 cells per degree, and use vec2mtx to rasterize
the boundary and generate a referencing vector for it:
gridDensity = 40;
[inGrid, inRefVec] = vec2mtx(inLat, inLon, gridDensity);
whos
Name
gridDensity
inGrid
inLat
inLon
inRefVec
indiana
Size
1x1
164x137
1x626
1x626
1x3
1x1
Bytes
8
179744
5008
5008
24
10960
Class
double
double
double
double
double
struct
The resulting grid contains doubles, and has 80 rows and 186 columns.
3 Make a map of the data grid in contrasting colors:
figure
axesm eqdcyl
meshm(inGrid, inRefVec)
colormap jet(4)
7-33
Manipulating Geospatial Data
4 Set up the map limits:
[latlim, lonlim] = limitm(inGrid, inRefVec);
setm(gca, 'Flatlimit', latlim, 'FlonLimit', lonlim)
tightmap
7-34
Manipulating Raster Geodata
5 To fill (recode) the interior of Indiana, you need a seed point (which must
be identified by row and column) and a seed value (to be allocated to all
cells within the polygon). Select the middle row and column of the grid and
choose an index value of 3 to identify the territory when calling encodem to
generate a new grid:
inPt = round([size(inGrid)/2, 3]);
inGrid3 = encodem(inGrid, inPt,1);
The last argument (1) identifies the code for boundary cells, where filling
should halt.
6 Clear and redraw the map using the filled grid:
meshm(inGrid3, inRefVec)
7-35
Manipulating Geospatial Data
7 Plot the original vectors on the grid to see how well data was rasterized:
plotm(inLat, inLon,'k')
The resulting map is shown on the left below. Use the Zoom tool on
the figure window to examine the gridding results more closely, as the
right-hand figure shows.
7-36
Manipulating Raster Geodata
See the vec2mtx and encodem reference pages for further information. imbedm
is a related function for gridding point values.
Using a GUI to Rasterize Polygons
In the previous example, had you wanted to include the states that border
Indiana, you could also have extracted Illinois, Kentucky, Ohio, and Michigan,
and then deleted unwanted areas of these polygons using maptrimp (see
Trimming Vector Data to a Rectangular Region on page 7-22 for specific
details on its use). Use the seedm function with seed points found using the
getseeds GUI to fill multiple polygons after they are gridded:
1 Extract the data for Indiana and its neighbors by passing their names in
a cell array to shaperead:
pcs = {'Indiana', 'Michigan', 'Ohio', 'Kentucky', 'Illinois'};
centralUS = shaperead('usastatelo.shp',...
'UseGeoCoords', true,...
'Selector',{@(name)any(strcmpi(name,pcs),2), 'Name'});
7-37
Manipulating Geospatial Data
meLat = [centralUS.Lat];
meLon = [centralUS.Lon];
2 Rasterize the trimmed polygons at a 1-arc-minute resolution (60 cells per
degree), also producing a referencing vector:
[meGrid, meRefVec] = vec2mtx(meLat, meLon, 60);
3 Set up a map figure and display the binary grid just created:
figure
axesm eqdcyl
geoshow(meLat, meLon, 'Color', 'r');
meshm(meGrid, meRefVec)
colormap jet(8)
4 Use getseeds to interactively pick seed points for Indiana, Michigan, Ohio,
Kentucky, and Illinois, in that order:
[row,col,val] = getseeds(meGrid, meRefVec, 5, [3 4 5 6 7]);
[row col val]
7-38
Manipulating Raster Geodata
ans =
207
219
212
56
393
140
326
506
459
433
3
4
5
6
7
The MATLAB prompt returns after you pick five locations in the figure
window. As you chose them yourself, your row and col numbers will differ.
5 Use encodem to fill each country with a unique value, producing a new grid:
meGrid5 = encodem(meGrid, [row col val], 1);
6 Clear the display and display meGrid5 to see the result:
clma
meshm(meGrid5, meRefVec)
The rasterized map of Indiana and its neighbors is shown below.
7-39
Manipulating Geospatial Data
See the getseeds reference page for more information. Themaptrim and
seedm GUI tools are also useful in this context.
Data Grids as Logical Variables
You can apply logical criteria to numeric data grids to create logical grids.
Logical grids are data grids consisting entirely of 1s and 0s. You can create
them by performing logical tests on data grid variables. The resulting binary
grid is the same size as the original grid(s) and can use the same referencing
vector, as the following hypothetical data operation illustrates:
logicalgrid = (realgrid > 0);
This transforms all values greater than 0 into 1s and all other values to 0s.
You can apply multiple conditions to a grid in one operation:
logicalgrid = (realgrid >- 100)&(realgrid < 100);
If several grids are the same size and share the same referencing vector (i.e.,
the grids are co-registered), you can create a logical grid by testing joint
conditions, treating the individual data grids as map layers:
logicalgrid = (population > 10000)&(elevation < 400)&...
(country == nigeria);
Several Mapping Toolbox functions enable the creation of logical grids using
logical and relational operators. Grids resulting from such operations contain
logical rather than numeric values (which reduce storage by a factor of 8), but
might need to be cast to double in order to be used in certain functions. Use
the onem and zerom functions to create grids of all 1s and all 0s.
Obtaining the Area Occupied by a Logical Grid Variable
You can analyze the results of logical grid manipulations to determine the
area satisfying one or more conditions (either coded as 1s or an expression
that yields a logical value of 1). The areamat function can provide the
fractional surface area on the globe associated with 1s in a logical grid. Each
grid element is a quadrangle, and the sum of the areas meeting the logical
condition provides the total area:
7-40
Manipulating Raster Geodata
1 You can use the topo grid and the greater-than relational operator to
determine what fraction of the Earth lies above sea level:
load topo
topoR = makerefmat('RasterSize', size(topo), ...
'Latlim', [-90 90], 'Lonlim', [0 360]);
a = areamat((topo > 0),topoR)
a =
0.2890
The answer is about 30%. (Note that land areas below sea level are
excluded.)
2 You can include a planetary radius in specified units if you want the result
to have those units. Here is the same query specifying units of square
kilometers:
a = areamat((topo > 0),topoR,almanac('earth','radius'))
a =
1.4739e+08
3 Use the usamtx data grid codes to find the area of a specific state within
the U.S.A. As an example, determine the area of the state of Texas, which
is coded as 46 in the usamtx grid:
load usamtx
a = areamat((map == 46), refvec, almanac('earth', 'radius'))
a =
6.2528e+005
The grid codes 625,277 square kilometers of land area as belonging to the
U.S.
4 You can construct more complex queries. For instance, using the last
example, compute what portion of the land area of the conterminous U.S.
7-41
Manipulating Geospatial Data
that Texas occupies (water and bordering countries are coded with 2 and
3, respectively):
usaland = areamat((map > 3 | map == 1), maplegend);
texasland = areamat((map == 46), maplegend);
texasratio = texasland/usaland
texasratio =
0.0735
This indicates that Texas occupies roughly 7.35% of the land area of the
U.S.
For further information, see the areamat reference page.
Data Grid Values Along a Path
A common application for gridded geodata is to calculate data values along a
path, for example, the computation of terrain height along a transect, a road,
or a flight path. The mapprofile function does this, based on numerical data
defining a set of waypoints, or by defining them interactively via graphic input
from a map display. Values computed for the resulting profile can be displayed
in a new plot or returned as output arguments for further analysis or display.
Using the mapprofile Function
The following example computes the elevation profile along a straight line:
1 Load the Korean elevation data:
figure;
load korea
2 Get its latitude and longitude limits using limitm and use them to set up
a map frame via worldmap:
[latlim, lonlim] = limitm(map, maplegend);
worldmap(latlim, lonlim)
worldmap plots only the map frame.
7-42
Manipulating Raster Geodata
3 Render the map and apply a digital elevation model (DEM) colormap to it:
meshm(map,maplegend,size(map),map)
demcmap(map)
4 Define endpoints for a straight-line transect through the region:
plat = [40.5 30.7];
plon = [121.5 133.5];
5 Compute the elevation profile, defaulting the track type to great circle
and the interpolation type to bilinear:
[z,rng,lat,lon] = mapprofile(map,maplegend,plat,plon);
6 Draw the transect in 3-D so it follows the terrain:
plot3m(lat,lon,z,'w','LineWidth',2)
7 Construct a plot of transect elevation and range:
7-43
Manipulating Geospatial Data
figure; plot(rng,z,'r')
The mapprofile function has other useful options, including the ability to
interactively define tracks and specify units of distance for them. For further
information, see the mapprofile reference page.
Data Grid Gradient, Slope, and Aspect
A map profile is often used to determine slopes along a path. A related
application is the calculation of slope at all points on a matrix. The gradientm
function uses a finite-difference approach to compute gradients for either a
regular or a georeferenced data grid. The function returns the components
of the gradient in the north and east directions (i.e., north-to-south,
east-to-west), as well as slope and aspect. The gradient components are
the change in the grid variable per meter of distance in the north and east
7-44
Manipulating Raster Geodata
directions. If the grid contains elevations in meters, the aspect and slope
are the angles of the surface normal clockwise from north and up from the
horizontal. Slope is defined as the change in elevation per unit distance along
the path of steepest ascent or descent from a grid cell to one of its eight
immediate neighbors, expressed as the arctangent. The angles are in units
of degrees by default.
Computing Gradient Data from a Regular Data Grid
The following example illustrates computation of gradient, slope, and aspect
data grids for a regular data grid based on the MATLAB peaks function:
1 Construct a 100-by-100 grid using the peaks function and construct a
referencing matrix for it:
datagrid = 500*peaks(100);
R = makerefmat('RasterSize',size(datagrid));
2 Use gradientm to generate grids containing aspect, slope, gradients to
north, and gradients to east:
[aspect,slope,gradN,gradE] = gradientm(datagrid,R);
whos
Name
aspect
datagrid
gradE
gradN
gridrv
slope
Size
100x100
100x100
100x100
100x100
1x3
100x100
Bytes
Class
80000
80000
80000
80000
24
80000
double
double
double
double
double
double
3 Map the surface data in a cylindrical equal area projection. Start with
the original elevations:
figure; axesm eqacyl
meshm(datagrid,R)
colormap (jet(64))
colorbar('vert')
7-45
Manipulating Geospatial Data
title('Peaks: elevation')
axis square
4 Clear the frame and display the slope grid:
figure; axesm eqacyl
meshm(slope,R)
colormap (jet(64))
colorbar('vert');
title('Peaks: slope')
5 Map the aspect grid:
figure; axesm eqacyl
meshm(aspect,R)
colormap (jet(64))
colorbar('vert');
title('Peaks: aspect')
6 Map the gradients to the north:
figure; axesm eqacyl
meshm(gradN,R)
colormap (jet(64))
colorbar('vert');
title('Peaks: North gradient')
7 Finally, map the gradients to the east:
figure; axesm eqacyl
meshm(gradE,R)
colormap (jet(64))
colorbar('vert');
title('Peaks: East gradient')
The maps of the peaks surface elevation and gradient data are shown below.
See the gradientm reference page for additional information.
7-46
Manipulating Raster Geodata
7-47
7-48
Manipulating Geospatial Data
8
Using Map Projections and
Coordinate Systems
All geospatial data must be flattened onto a display surface in order to visually
portray what exists where. The mathematics and craft of map projection are
central to this process. Although there is no limit to the ways geodata can
be projected, conventions, constraints, standards, and applications generally
prescribe its usage. This chapter describes what map projections are, how
they are constructed and controlled, their essential properties, and some
possibilities and limitations.
What Is a Map Projection? on page 8-2
Quantitative Properties of Map Projections on page 8-3
The Three Main Families of Map Projections on page 8-5
Projection Aspect on page 8-10
Projection Parameters on page 8-18
Visualizing and Quantifying Projection Distortions on page 8-27
Accessing, Computing, and Inverting Map Projection Data on page 8-37
Working with the UTM System on page 8-51
Summary and Guide to Projections on page 8-63
If you are not acquainted with the types, properties, and uses of map
projections, read the first four sections. When constructing mapsespecially
in an environment in which a variety of projections are readily availableit is
important to understand how to evaluate projections to select one appropriate
to the contents and purpose of a given map.
Using Map Projections and Coordinate Systems
What Is a Map Projection?
Human beings have known that the shape of the Earth resembles a sphere
and not a flat surface since classical times, and possibly much earlier than
that. If the world were indeed flat, cartography would be much simpler
because map projections would be unnecessary.
To represent a curved surface such as the Earth in two dimensions, you must
geometrically transform (literally, and in the mathematical sense, map) that
surface to a plane. Such a transformation is called a map projection. The
term projection derives from the geometric methods that were traditionally
used to construct maps, in the fashion of optical projections made with a
device called camera obscura that Renaissance artists relied on to render
three-dimensional perspective views on paper and canvas.
While many map projections no longer rely on physical projections, it is useful
to think of map projections in geometric terms. This is because map projection
consists of constructing points on geometric objects such as cylinders, cones,
and circles that correspond to homologous points on the surface of the planet
being mapped according to certain rules and formulas.
The following sections describe the basic properties of map projections,
the surfaces onto which projections are developed, the types of parameters
associated with different classes of projections, how projected data can be
mapped back to the sphere or spheroid it represents, and details about one
very widely used projection system, called Universal Transverse Mercator.
Note Most map projections in the toolbox are implemented as M-functions;
however, these are only used by certain calling functions (such as geoshow
and axesm), and thus have no documented public API.
For more detailed information on specific projections, browse the Chapter
14, Map Projections Reference (available online and in the PDF version of
this document). For further reading, Appendix A, Bibliography provides
references to books and papers on map projection.
8-2
Quantitative Properties of Map Projections
Quantitative Properties of Map Projections
A sphere, unlike a polyhedron, cone, or cylinder, cannot be reformed into a
plane. In order to portray the surface of a round body on a two-dimensional
flat plane, you must first define a developable surface (i.e., one that can be cut
and flattened onto a plane without stretching or creasing) and devise rules for
systematically representing all or part of the spherical surface on the plane.
Any such process inevitably leads to distortions of one kind or another. Five
essential characteristic properties of map projections are subject to distortion:
shape, distance, direction, scale, and area. No projection can retain more than
one of these properties over a large portion of the Earth. This is not because
a sufficiently clever projection has yet to be devised; the task is physically
impossible. The technical meanings of these terms are described below.
Shape (also called conformality)
Shape is preserved locally (within small areas) when the scale of a map at
any point on the map is the same in any direction. Projections with this
property are called conformal. In them, meridians (lines of longitude) and
parallels (lines of latitude) intersect at right angles. An older term for
conformal is orthomorphic (from the Greek orthos, straight, and morphe,
shape).
Distance (also called equidistance)
A map projection can preserve distances from the center of the projection
to all other places on the map (but from the center only). Such a map
projection is called equidistant. Maps are also described as equidistant
when the separation between parallels is uniform (e.g., distances along
meridians are maintained). No map projection maintains distance
proportionality in all directions from any arbitrary point.
Direction
A map projection preserves direction when azimuths (angles from the
central point or from a point on a line to another point) are portrayed
correctly in all directions. Many azimuthal projections have this property.
Scale
Scale is the ratio between a distance portrayed on a map and the same
extent on the Earth. No projection faithfully maintains constant scale over
large areas, but some are able to limit scale variation to one or two percent.
8-3
Using Map Projections and Coordinate Systems
Area (also called equivalence)
A map can portray areas across it in proportional relationship to the
areas on the Earth that they represent. Such a map projection is called
equal-area or equivalent. Two older terms for equal-area are homolographic
or homalographic (from the Greek homalos or homos, same, and graphos,
write), and authalic (from the Greek autos, same, and ailos, area), and
equireal. Note that no map can be both equal-area and conformal.
For a complete description of the properties that specific map projections
maintain, see Summary and Guide to Projections on page 8-63.
8-4
The Three Main Families of Map Projections
The Three Main Families of Map Projections
In this section...
Unwrapping the Sphere to a Plane on page 8-5
Cylindrical Projections on page 8-5
Conic Projections on page 8-7
Azimuthal Projections on page 8-8
Unwrapping the Sphere to a Plane
Mapmakers have developed hundreds of map projections, over several
thousand years. Three large families of map projection, plus several smaller
ones, are generally acknowledged. These are based on the types of geometric
shapes that are used to transfer features from a sphere or spheroid to a
plane. As described above, map projections are based on developable surfaces,
and the three traditional families consist of cylinders, cones, and planes.
They are used to classify the majority of projections, including some that
are not analytically (geometrically) constructed. In addition, a number of
map projections are based on polyhedra. While polyhedral projections have
interesting and useful properties, they are not described in this guide.
Which developable surface to use for a projection depends on what region
is to be mapped, its geographical extent, and the geometric properties that
areas, boundaries, and routes need to have, given the purpose of the map.
The following sections describe and illustrate how the cylindrical, conic, and
azimuthal families of map projections are constructed and provides some
examples of projections that are based on them.
Cylindrical Projections
A cylindrical projection is produced by wrapping a cylinder around a globe
representing the Earth. The map projection is the image of the globe projected
onto the cylindrical surface, which is then unwrapped into a flat surface.
When the cylinder aligns with the polar axis, parallels appear as horizontal
lines and meridians as vertical lines. Cylindrical projections can be either
equal-area, conformal, or equidistant. The following figure shows a regular