www.gusucode.com > map 案例源码 matlab代码程序 > map/mapexkmlexport.m

    %% Exporting Vector Data to KML
%
% This example shows how to structure geographic point, line, and polygon
% vector data and export it to a Keyhole Markup Language (KML) file. KML is
% an XML-based markup language designed for visualizing geographic data on
% Web-based maps or "Earth browsers", such as Google Earth(TM), Google
% Maps(TM), NASA WorldWind, and the ESRI(R) ArcGIS(TM) Explorer.
% 
% The following functions write geographic data to a KML file:
%
% * <https://www.mathworks.com/help/map/ref/kmlwritepoint.html kmlwritepoint> Write geographic points to KML file
% * <https://www.mathworks.com/help/map/ref/kmlwriteline.html kmlwriteline> Write geographic line to KML file
% * <https://www.mathworks.com/help/map/ref/kmlwritepolygon.html kmlwritepolygon> Write geographic polygon to KML file
% * <https://www.mathworks.com/help/map/ref/kmlwrite.html kmlwrite>  Write geographic data to KML file

% Copyright 2007-2016 The MathWorks, Inc.

%% Define an Output Folder for the KML Files
% This example creates several KML files and uses the variable |kmlFolder|
% to denote their location. The value used here is determined by the output
% of the |tempdir| command, but you could easily customize this. 
kmlFolder = tempdir;

%%
% Create a cell array of the KML file names used in this example in order
% to optionally remove them from your KML output folder when the example
% ends.
kmlFilenames = {};

%% Create a Function Handle to Open an Earth Browser
% A KML file can be opened in a variety of "Earth browsers", Web maps, or
% an editor. You can customize the following anonymous function handle to
% open a KML file. Executing this function handle launches the Google Earth
% browser, which must be installed on your computer. You can use the
% application by assigning the variable |useApplication| to |true| in your
% workspace or assign it to |true| here.
useApplication = exist('useApplication','var') && useApplication;

%%
if useApplication
    if ispc
        % On Windows(R) platforms display the KML file with:
        openKML = @(filename) winopen(filename);
    elseif ismac
        % On Mac platforms display the KML file with:
        cmd = 'open -a Google\ Earth ';
        openKML = @(filename) system([cmd filename]);
    else
        % On Linux platforms display the KML file with:
        cmd = 'googleearth ';
        openKML = @(filename) system([cmd filename]);
    end
else
    % No "Earth browser" is installed on the system.
    openKML = @(filename) disp('');
end

%% Example 1: Write Single Point to KML File
% This example writes a single point to a KML file.

%%
% Assign latitude and longitude values for Paderborn, Germany.
lat = 51.715254;
lon = 8.75213;

%%
% Use |kmlwritepoint| to write the point to a KML file.
filename = fullfile(kmlFolder,'Paderborn.kml');
kmlwritepoint(filename,lat,lon);

%%
% Open the KML file.
openKML(filename)

%%
% Add |filename| to |kmlFilenames|.
kmlFilenames{end+1} = filename;

%% Example 2: Write Single Point to KML File with Icon and Description
% This example writes a single point to a KML file. The placemark includes
% an icon and a description with HTML markup.

%%
% Assign latitude and longitude coordinates for a point that locates the
% headquarters of MathWorks(R) in Natick, Massachusetts.
lat = 42.299827;
lon = -71.350273;

%%
% Create a description for the placemark. Include HTML tags in the
% description to add new lines for the address.
description = sprintf('%s<br>%s</br><br>%s</br>', ...
   '3 Apple Hill Drive', 'Natick, MA. 01760', ...
   'https://www.mathworks.com');

%%
% Assign |iconFilename| to a GIF file on the local system's network.
iconDir = fullfile(matlabroot,'toolbox','matlab','icons');
iconFilename = fullfile(iconDir,'matlabicon.gif');

%%
% Assign the name for the placemark.
name = 'The MathWorks, Inc.';

%%
% Use |kmlwritepoint| to write the point and associated data to the KML
% file.
filename = fullfile(kmlFolder,'MathWorks.kml');
kmlwritepoint(filename,lat,lon,'Description',description,'Name',name, ...
   'Icon',iconFilename);

%%
% Open the KML file.
openKML(filename)

%%
% Add |filename| to |kmlFilenames|.
kmlFilenames{end+1} = filename;

%% Example 3: Write Multiple Points to KML File
% This example writes the locations of major European cities to a KML file,
% including the names of the cities, and removes the default description
% table.

%%
% Assign the latitude, longitude bounding box.
latlim = [ 30; 75];
lonlim = [-25; 45];

%%
% Read the data from the |worldcities| shapefile into a geostruct array.
cities = shaperead('worldcities.shp','UseGeoCoords',true, ...
    'BoundingBox',[lonlim, latlim]);

%%
% Convert to a geopoint vector.
cities = geopoint(cities);

%%
% Use |kmlwrite| to write the geopoint vector to a KML file. Assign the
% name of the placemark to the name of the city.  Remove the default
% description since the data has only one attribute.
filename = fullfile(kmlFolder,'European_Cities.kml');
kmlwrite(filename,cities,'Name',cities.Name,'Description',{});

%%
% Open the KML file.
openKML(filename)

%%
% Add |filename| to |kmlFilenames|.
kmlFilenames{end+1} = filename;

%% Example 4: Write Multiple Points to KML File with Modified Attribute Table
% This example writes placemarks at the locations of tsunami (tidal wave)
% events, reported over several decades and tagged geographically by
% source location, to a KML file.

%%
% Read the data from the tsunamis shapefile.
tsunamis = shaperead('tsunamis','UseGeoCoords',true);

%%
% Convert to a geopoint vector.
tsunamis = geopoint(tsunamis);

%%
% Sort the attributes.
tsunamis = tsunamis(:, sort(fieldnames(tsunamis)));
   
%%
% Construct an attribute specification.
attribspec = makeattribspec(tsunamis);

%%
% Modify the attribute specification to:
%%
% * Display Max_Height, Cause, Year, Location, and Country attributes 
% * Rename the 'Max_Height' field to 'Maximum Height' 
% * Highlight each attribute label with a bold font 
% * Set to zero the number of decimal places used to display Year
% * We have independent knowledge that the height units are meters, 
%   so we will add that to the Height format specifier
desiredAttributes = {'Max_Height','Cause','Year','Location','Country'};
allAttributes = fieldnames(attribspec);
attributes = setdiff(allAttributes, desiredAttributes);
attribspec = rmfield(attribspec, attributes);
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>';

%%
% Use |kmlwrite| to write the geopoint vector containing the selected
% attributes and source locations to a KML file.
filename = fullfile(kmlFolder, 'Tsunami_Events.kml');
name = tsunamis.Location;
kmlwrite(filename,tsunamis,'Description',attribspec,'Name',name)

%%
% Open the KML file.
openKML(filename)

%%
% Add |filename| to |kmlFilenames|.
kmlFilenames{end+1} = filename;

%% Example 5: Write Single Point with a LookAt Virtual Camera to KML File
% This example writes a single point with a LookAt virtual camera near
% Machu Picchu, Peru
 
%%
% Use a geopoint vector to define a LookAt virtual camera.
lat = -13.163111;
lon = -72.544945;
lookAt = geopoint(lat,lon);
lookAt.Range = 1500;
lookAt.Heading = 260;
lookAt.Tilt = 67;

%%
% Use |kmlwritepoint| to write the point location and LookAt information.
filename = fullfile(kmlFolder, 'Machu_Picchu.kml');
alt = 2430;
name = 'Machu Picchu';
kmlwritepoint(filename,lat,lon,alt,'LookAt',lookAt,'Name',name);

%%
% Open the KML file.
openKML(filename)

%%
% Add |filename| to |kmlFilenames|.
kmlFilenames{end+1} = filename;

%% Example 6: Write Single Point with a Camera to KML File
% This example writes a single point with a camera view of the Washington
% Monument in Washington D.C to a KML file. The marker is placed at the
% ground location of the camera.

%%
% Construct the camera.
camlat = 38.889301;
camlon = -77.039731;
camera = geopoint(camlat,camlon);
camera.Altitude = 500;
camera.Heading = 90;
camera.Tilt = 45;
camera.Roll = 0;

%%
% Use |kmlwritepoint| to write the point location and Camera information.
name = 'Camera ground location';
lat = camera.Latitude;
lon = camera.Longitude;
filename = fullfile(kmlFolder,'WashingtonMonument.kml');
kmlwritepoint(filename,lat,lon,'Camera',camera,'Name',name)
 
%%
% Open the KML file.
openKML(filename)

%%
% Add |filename| to |kmlFilenames|.
kmlFilenames{end+1} = filename;


%% Example 7: Write Address Data to KML File
% This example writes unstructured address data to a KML file. 

%%
% Create a cell array containing names of several places of interest in the
% Boston area.
names = {'Boston', ...
    'Massachusetts Institute of Technology', ...
    'Harvard University', ...
    'Fenway Park', ...
    'North End'};

%%
% Create a cell array containing addresses for the places of interest in
% the Boston area.
addresses = { ...
    'Boston, MA', ...
    '77 Massachusetts Ave, Cambridge, MA 02139', ...
    'Massachusetts Hall, Cambridge MA 02138', ...
    '4 Yawkey Way, Boston, MA', ...
    '134 Salem St, Boston, MA'};

%%
% Use a Google Maps icon for each of the placemarks.
icon = 'http://maps.google.com/mapfiles/kml/paddle/red-circle.png';

%%
% Use |kmlwrite| to write the cell array of addresses to the KML file.
filename = fullfile(kmlFolder, 'Places_of_Interest.kml');
kmlwrite(filename,addresses,'Name',names,'Icon',icon,'IconScale',1.5);
    
%%
% Open the KML file.
openKML(filename)

%%
% Add |filename| to |kmlFilenames|.
kmlFilenames{end+1} = filename;

%% Example 8: Write Single Line to KML File
% This example writes a single line connecting the top of Mount Washington
% to the Mount Washington Hotel in Carroll, New Hampshire, to a KML file.

%% 
% Assign coordinate values for the region of interest.
lat_Mount_Washington = 44.270489039;
lon_Mount_Washington = -71.303246453;

lat_Mount_Washington_Hotel = 44.258056;
lon_Mount_Washington_Hotel = -71.440278;

lat = [lat_Mount_Washington lat_Mount_Washington_Hotel];
lon = [lon_Mount_Washington lon_Mount_Washington_Hotel];

%%
% Set the altitude to 6 feet, for the approximate height of a person.
alt = 6 * unitsratio('meters', 'feet');

%%
% Add a camera viewpoint from the Mount Washington Hotel.
clat = lat(2);
clon = lon(2);
camera = geopoint(clat,clon,'Altitude',2,'Tilt',90,'Roll',0,'Heading',90);

%%
% Use |kmlwriteline| to write the arrays to a KML file.
filename = fullfile(kmlFolder, 'Mount_Washington.kml');
name = 'Mount Washington';
kmlwriteline(filename,lat,lon,alt,'Name',name,'Color','k','Width',3, ...
    'Camera',camera,'AltitudeMode','relativeToGround');

%%
% Open the KML file.
openKML(filename)

%%
% Add |filename| to |kmlFilenames|.
kmlFilenames{end+1} = filename;

%% Example 9: Write GPS Track Log to KML File
% This example writes a GPS track log to a KML file.

%%
% Read the track log from the GPX file. The data in the track log was
% obtained from a GPS wristwatch held while gliding over Mount Mansfield in
% Vermont, USA, on August 28, 2010.
track = gpxread('sample_mixed','FeatureType','track');

%%
% Use |kmlwriteline| to write the track log to a KML file. The elevation
% values obtained by the GPS are relative to sea level.
filename = fullfile(kmlFolder, 'GPS_Track_Log.kml');
lat = track.Latitude;
lon = track.Longitude;
alt = track.Elevation;
name = 'GPS Track Log';
kmlwriteline(filename,lat,lon,alt,'Name',name,'Color','k','Width',2, ...
    'AltitudeMode','relativeToSeaLevel');

%%
% Open the KML file.
openKML(filename)

%%
% Add |filename| to |kmlFilenames|.
kmlFilenames{end+1} = filename;

%% Example 10: Write Circles to KML File
% This example writes circles as lines around London City Airport to a KML
% file. The example includes a |LookAt| virtual camera.

%%
% Assign latitude and longitude values for the center of the feature.
lat0 = 51.50487;
lon0 = .05235;

%%
% Assign |azimuth| to [] to compute a complete small circle. Use the WGS84
% ellipsoid.
azimuth = [];
spheroid = wgs84Ellipsoid;

%%
% Compute small circles of 3000, 2000, and 1000 meter radius. Assign a
% color value of |'blue'|, |'green'|, and |'red'| for each circle. Assign
% an elevation value of 100 meters (above ground) for each circle. Use a
% line geoshape vector to contain the data.
radius = 3000:-1000:1000;
colors = {'blue','green','red'};
elevation = 100;
circles = geoshape(0,0,'Name','','Color','','Elevation',elevation);
for k = 1:length(radius)
    [lat, lon] = scircle1(lat0,lon0,radius(k),azimuth,spheroid);
    circles(k).Latitude = lat;
    circles(k).Longitude = lon;
    circles(k).Name = [num2str(radius(k)) ' Meters'];
    circles(k).Color = colors{k};
    circles(k).Elevation = elevation;
end

%%
% Use a geopoint vector to define a LookAt virtual camera with a viewpoint
% from the east of the airport and aligned with the runway.
lat = 51.503169;
lon =  0.105478;
range = 3500;
heading = 270;
tilt =  60;
lookAt = geopoint(lat,lon,'Range',range,'Heading',heading,'Tilt',tilt);

%%
% Use |kmlwrite| to write the geoshape vector containing the circles and
% associated data to a KML file.
filename = fullfile(kmlFolder,'Small_Circles.kml');
kmlwrite(filename,circles,'AltitudeMode','relativeToGround','Width',2, ...
    'Name',circles.Name,'Color',circles.Color,'LookAt',lookAt);

%%
% Open the KML file. Using Google Earth, the |LookAt| view point is set
% when clicking on either one of the |1000 Meters|, |2000 Meters|, or |3000
% Meters| strings in the Places list.
openKML(filename)

%%
% Add |filename| to |kmlFilenames|.
kmlFilenames{end+1} = filename;

%% Example 11: Write Circular Polygons to KML File
% This example writes circular polygons around London City Airport to a
% KML file. It includes a |LookAt| virtual camera and uses the same data
% calculated in step 9.

%%
% Change the |Geometry| property value of the geoshape vector to
% |'polygon'|. The polygons are drawn in the same order as the geoshape
% vector and are indexed from largest to smallest radii, thus each polygon
% will be visible in the browser.
circles.Geometry = 'polygon';

%%
% Change the elevation of each polygon.
circles.Elevation = 1000:1000:3000;

%%
% Use a geopoint vector to define a LookAt virtual camera with a viewpoint
% from the east of the airport, aligned with the runway, and with a view
% of all three polygons.
lat = 51.501587;
lon = 0.066147;
range = 13110;
heading = 270;
tilt = 60;
lookAt = geopoint(lat,lon,'Range',range,'Heading',heading,'Tilt',tilt);
 
%%
% Use |kmlwrite| to write the polygon geoshape vector containing the
% circular polygons and associated data to a KML file. Extrude the polygons
% to the ground. Set the polygon edge color to black and assign a face
% alpha value to provide visibility inside the polygon.
filename = fullfile(kmlFolder,'Small_Circle_Polygons.kml');
name = circles.Name;
color = circles.Color;
kmlwrite(filename,circles,'AltitudeMode','relativeToGround','Extrude',true, ...
    'Name',name,'FaceColor',color,'EdgeColor','k','FaceAlpha',.6,'LookAt',lookAt);

%%
% Open the KML file. Using Google Earth, the |LookAt| view point is set
% when clicking on either one of the |1000 Meters|, |2000 Meters|, or |3000
% Meters| strings in the Places list.
openKML(filename)

%%
% Add |filename| to |kmlFilenames|.
kmlFilenames{end+1} = filename;

%% Example 12: Write Polygon Data from Shapefile to KML file
% This example writes polygon data from the |usastatelo| shapefile to a KML
% file. The polygon faces are set with a color appropriate for political
% regions. The polygon faces are set with an alpha value to provide
% visibility inside the polygon.
states = shaperead('usastatelo','UseGeoCoords',true);
states = geoshape(states);
colors = polcmap(length(states));
name = states.Name;
filename = fullfile(kmlFolder,'usastatelo.kml');
kmlwrite(filename,states,'Name',name,'FaceColor',colors,'FaceAlpha',.6, ...
    'EdgeColor','k')
    
%%
% Open the KML file.
openKML(filename)

%%
% Add |filename| to |kmlFilenames|.
kmlFilenames{end+1} = filename;


%% Example 13: Write Polygon Contours to KML File
% This example contours a grid in a local coordinate system, returns the
% contours in a geographic system, and writes the polygon contours to a KML
% file.

%%
% Create a grid in a local system.
X = -150000:10000:150000;
Y =  0:10000:300000;
[xmesh, ymesh] = meshgrid(X/50000, (Y - 150000)/50000);
Z = 8 + peaks(xmesh, ymesh);

%%
% Define a local geodetic origin near Frankfurt, Germany and an
% ellipsoidal height.
lat0 = 50.108;
lon0 = 8.6732;
h0 = 100;

%%
% Define contour levels.
levels = 0:2:18;

%%
% Contour the grid and return the output in a polygon geoshape vector.
[~, contourPolygons] = geocontourxy(X,Y,Z,lat0,lon0,h0,'LevelList',levels);

%%
% Output the contours to a KML file. Set the faces with an alpha value.
% Set |CutPolygons| to |false| since the altitude values are not uniform.
% Clamp the polygons to the ground.
colors = parula(length(contourPolygons));
filename = fullfile(kmlFolder,'Contour_Polygons.kml');
kmlwrite(filename,contourPolygons,'FaceColor',colors,'FaceAlpha',.6, ...
    'EdgeColor','k','CutPolygons',false,'AltitudeMode','clampToGround')
   
%%
% Open the KML file.
openKML(filename)

%%
% Add |filename| to |kmlFilenames|.
kmlFilenames{end+1} = filename;

%% Example 14: Write Polygon with Inner Ring to KML File
% This example constructs a polygon with an inner ring around the Eiffel
% Tower and writes the polygon to a KML file. The polygon's altitude is set
% to 500 meters above ground.
lat0 = 48.858288;
lon0 = 2.294548;
outerRadius = .02;
innerRadius = .01;
[lat1,lon1] = scircle1(lat0,lon0,outerRadius);
[lat2,lon2] = scircle1(lat0,lon0,innerRadius);
[lon2,lat2] = poly2ccw(lon2,lat2);
lat = [lat1; NaN; lat2];
lon = [lon1; NaN; lon2];
alt = 500;
filename = fullfile(kmlFolder,'EiffelTower.kml');

%%
% Export the polygon to a KML file. Set the edge color to black, the face
% color to cyan, and the face alpha value.
kmlwritepolygon(filename,lat,lon,alt,'EdgeColor','k','FaceColor','c', ...
    'FaceAlpha',.5)
 
%%
% Open the KML file.
openKML(filename)

%%
% Add |filename| to |kmlFilenames|.
kmlFilenames{end+1} = filename;

%% Delete Generated KML Files
% Optionally, delete the new KML files from your KML output folder.
if ~useApplication
    for k = 1:length(kmlFilenames)
        delete(kmlFilenames{k})
    end
end

%% Credits
% worldcities.shp
%
%    Data from the Digital Chart of the World (DCW) browser layer,
%    published by U.S. National Geospatial-Intelligence Agency (NGA),
%    formerly National Imagery and Mapping Agency (NIMA).
%
% tsunamis.shp
%
%    Data from Global Tsunami Database, U.S. National Geospatial Data
%    Center (NGDC), National Oceanic and Atmospheric Administration (NOAA)
%
% usastatelo.shp
%
%    Based on data from the CIA World DataBank II and the U.S. Census
%    Bureau site "State and County QuickFacts".