Skip to Main Content Skip to Search
Product Documentation

Your First Maps

This section helps you exercise high-level functions and GUIs to map and display geodata. It introduces worldmap and other basic functions, and then describes how to use the Map Viewer (mapview).

Create a World Map

Spatial data refers to data describing location, shape, and spatial relationships. 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 process. Mapping Toolbox functions handle many of the details of loading and displaying data, and built-in data structures facilitate data storage. Nevertheless, the more you understand about your data and the capabilities of the toolbox, the more interesting applications you can pursue, and the more useful your results will be to you and others.

Follow this example to create your first world map.

  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 selects a reasonable choice for your map projection and coordinate limits. In this case, it chose a Robinson projection centered on the prime meridian and the equator (0º latitude, 0º longitude).

    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—a set of discrete vertices that, when connected in the order given, approximate the coastlines of continents, major islands, and inland seas. The vertex latitudes and longitudes are stored as MATLAB vectors in a MAT-file. First, list the variables in the file:

    whos -file coast.mat
    

    The output is shown below:

    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, transforms them to x and y via a specified map projection, and displays them in a figure axes. In this example, worldmap specifies the projection.

      Note   Certain Mapping Toolbox functions that end with m, such as plotm and textm, are modeled after familiar MATLAB functions that handle non-geographic coordinate data.

  4. 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 display breaks into separate parts like this because in the vectors lat and long the vertices of various coastlines are concatenated together but separated by isolated NaN-valued elements. In other words, "NaN separators" implicitly divide each vector into multiple parts. lat and long include "NaN terminators" as well as separators, showing that the coast data set is organized into precisely 241 polygons.

    Enter the following code to break out your data into its NaN-separated parts:

    [latcells, loncells] = polysplit(lat, long);
    numel(latcells)
    

    latcells and loncells are cell vectors, with each cell containing the vertices of just one polygon part. The number of parts appears:

    ans =
       241
  5. 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 access and modify these properties.

  6. To inspect the MapProjection property for the map of Europe, type:

    getm(h, 'MapProjection')

    The type of projection appears:

    ans =
    eqdconic

    If you're not familiar with the abbreviation "eqdconic," type:

    help eqdconic

    To see all the map-specific properties for this map axes, type:

    getm(h)
  7. Add data to the map of Europe by using the geoshow function to import and display several shapefiles in the toolbox/map/mapdata folder:

    geoshow('landareas.shp', 'FaceColor', [0.15 0.5 0.15])
    geoshow('worldlakes.shp', 'FaceColor', 'cyan')
    geoshow('worldrivers.shp', 'Color', 'blue')
    geoshow('worldcities.shp', 'Marker', '.',...
                               'Color', 'red')

    Note how geoshow can plot data directly from files onto a map axes without first importing 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')

To learn more about display properties for map axes and how to control them, see Accessing and Manipulating Map Axes Properties.

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; and list data attributes. You can display selected data attributes 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. 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.

    In the Map Viewer graphic, you can see arrows pointing to the X and Y coordinate readouts. The Map Viewer is designed primarily for working with data sets that refer to a projected map coordinate system (as opposed to a geographic, latitude-longitude system), so the coordinate axes are named X and Y.

  2. For ease in importing Mapping Toolbox demo data, set your working folder. Type the following in the Command Window:

    cd(fullfile(matlabroot,'toolbox','map','mapdata'))
  3. You can also navigate to this folder with the Map Viewer Import Data dialog if you prefer. In the Map Viewer, select the File menu and then choose Import From File. Open the GeoTIFF file boston.tif, 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_metadata.txt. To open boston.txt, type the following at the command line:

    open 'boston.txt'
  4. To see the map scale in the Map Viewer, 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 Map Viewer now looks like this.

    The cursor in the picture has been placed so that it points 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, enter the following code to import a vector data layer, the streets and highways in the central Boston area:

    boston_roads = shaperead('boston_roads.shp');
    

    The shaperead function reads the line shapefile boston_roads.shp into the workspace as a geographic data structure. As is frequently the case when overlaying geodata, the coordinate system used by boston_roads.shp (in units of meters) does not completely agree with the one for the satellite image, boston.tif (in units of feet). If you were to ignore this, the two data sets would be out of registration by a large distance.

  7. Convert the X and Y coordinate fields of boston_roads.shp from meters to U.S. survey feet:

    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.

  8. In the Map Viewer File menu, select Import From Workspace > Vector Data > Geographic Data Structure. 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 the Map Viewer needs is now loaded into it.

  9. 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 may differ.

  10. Use the Active layer drop-down menu at the bottom right to select boston_roads. Changing the active layer has no visual effect. Doing so allows you to query attributes of the layer you select. You can designate any layer to be the active layer; it does not need to be the topmost layer. By default, the first layer imported is active.

  11. 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 attributes of the selected object.

    The selected road is Massachusetts Avenue (Route 2A). As the above figure shows, the boston_roads vectors have six attributes, including an implicit INDEX attribute added by the Map Viewer.

  12. Get information about some other roads. Dismiss open Info windows by clicking their close boxes.

  13. Choose an attribute for the Datatip tool to inspect. From the Layers menu, select boston_roads > Set Label Attribute. From the list in the Attribute Names dialog, select CLASS and click OK to dismiss it.

  14. Select the Datatip tool. The cursor assumes a crosshairs (+) shape. A dialog box appears to remind you how to change attributes. Click OK to dismiss the box.

  15. Use the Datatip tool to identify the administrative class of any road displayed. When you click on a road segment, a datatip is left in that place to indicate the CLASS attribute of the active layer, as illustrated below.

  16. 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]})
    

    The following output appears:

    roadcolors = 
        ShapeType: 'Line'
            Color: {6x3 cell}
  17. The Map Viewer recognizes and imports symbolspecs from the workspace. To apply the one you just created, from the Layers menu, select boston_roads > Set Symbol Spec. From the Layer Symbols dialog, select the roadcolors symbolspec you just created and click OK. After the Map Viewer has read and applied the symbolspec, the map looks like this.

  18. Remove the datatips before going on. To dismiss datatips, right-click one of them and select Delete all datatips from the pop-up context menu that appears.

  19. Add another layer, a set of points that identifies 13 Boston landmarks. As you did with the boston_roads layer, import it from a shapefile:

    boston_placenames = shaperead('boston_placenames.shp');
    
  20. The locations for these landmarks are given in meters, so you must convert their coordinates to units of survey feet before importing them into Map Viewer:

    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
    
  21. From the File menu, select Import From Workspace > Vector Data > Geographic Data Structure. Choose boston_placenames as the data to import from the workspace and click OK.

  22. The boston_placenames markers are symbolized as small x markers, but these markers do not show up over the orthophoto. To solve this problem, create a symbolspec for the markers to represent them as red filled circles. At the MATLAB command line, type:

    places = makesymbolspec('Point',{'Default','Marker','o', ...
    'MarkerEdgeColor','r','MarkerFaceColor','r'})

    The following output appears:

    places = 
    
              ShapeType: 'Point'
                 Marker: {'Default'  ''  'o'}
        MarkerEdgeColor: {'Default'  ''  'r'}
        MarkerFaceColor: {'Default'  ''  '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.

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

  24. 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 datatips you show).

  25. 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 774,011 and the Y readout is roughly 2,955,615; and click once to enlarge the view. The scale changes to about 1:12,500 and the map appears as below.

  26. From the Tools menu, choose Select Annotations to change from the Datatip tool back to the original cursor. 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 map.

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

  28. In order to be able to save a file in the next step, change your working folder to a writable folder, such as /work.

  29. Save your selection as an image file. From the File menu, select Save As Raster Map > Selected Area to open an Export to File dialog.

    In the Export to File dialog, navigate to a folder 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 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 show you how to read worldfiles and display a georeferenced image outside of mapview.

  30. 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 the map with mapshow:

    [X cmap] = imread('central_boston.tif');
    R = worldfileread('central_boston.tfw');
    figure
    mapshow(X, cmap, R);

    See the documentation for mapshow for another example of displaying a georeferenced image.

  31. 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. For more information about the Map Viewer, see the mapview reference page.

  32. The two examples in the Getting Started chapter provide an introduction to the Mapping Toolbox. To find out what else the toolbox can do, run the demos described in Mapping Toolbox Demos and Data. If you have a specific task in mind and want to see a similar problem solved, search the index of examples.

  


Recommended Products

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

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