Products & Services Industries Academia Support User Community Company

Learn more about Mapping Toolbox   

Your First Maps

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 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).

    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            Bytes  Class     Attributes
    
      lat       9865x1             78920  double              
      long      9865x1             78920  double              
    
  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.

    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');

    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 figure's 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 =
    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')

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. 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.

    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.

    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.

    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 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.

    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.

    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.

    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.

  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.

  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}
  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.

    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.

    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 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.

  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.

  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 area's 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)

    • 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, 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 layer's 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 window's close box or select Close from the File menu.

  


Recommended Products

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.

 © 1984-2009- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS