1 function kmlStruct = kml2struct(kmlFile)
2 % kmlStruct = kml2struct(kmlFile)
4 % Import a .kml file as a vector array of shapefile structs, with Geometry, Name,
5 % Description, Lon, Lat, and BoundaryBox fields. Structs may contain a mix
6 % of points, lines, and polygons.
8 % .kml files with folder structure will not be presented as such, but will
9 % appear as a single vector array of structs.
11 % downloaded from https://www.mathworks.com/matlabcentral/fileexchange/35642-kml2struct
12 % author james slegers
14 [FID msg] = fopen(kmlFile,'rt');
18 txt = fread(FID,'uint8=>char')';
20 expr = '<Placemark.+?>.+?</Placemark>';
21 objectStrings = regexp(txt,expr,'match');
22 Nos = length(objectStrings);
24 % Find Object Name Field
25 bucket = regexp(objectStrings{ii},'<name.*?>.+?</name>','match');
30 name = regexprep(bucket{1},'<name.*?>\s*','');
31 name = regexprep(name,'\s*</name>','');
34 % Find Object Description Field
35 bucket = regexp(objectStrings{ii},'<description.*?>.+?</description>','match');
40 desc = regexprep(bucket{1},'<description.*?>\s*','');
41 desc = regexprep(desc,'\s*</description>','');
45 % Identify Object Type
46 if ~isempty(regexp(objectStrings{ii},'<Point', 'once'))
48 elseif ~isempty(regexp(objectStrings{ii},'<LineString', 'once'))
50 elseif ~isempty(regexp(objectStrings{ii},'<Polygon', 'once'))
65 % Find Coordinate Field
66 bucket = regexp(objectStrings{ii},'<coordinates.*?>.+?</coordinates>','match');
68 coordStr = regexprep(bucket{1},'<coordinates.*?>(\s+)*','');
69 coordStr = regexprep(coordStr,'(\s+)*</coordinates>','');
70 % Split coordinate string by commas or white spaces, and convert string
72 coordMat = str2double(regexp(coordStr,'[,\s]+','split'));
73 % Rearrange coordinates to form an x-by-3 matrix
74 [m,n] = size(coordMat);
75 coordMat = reshape(coordMat,3,m*n/3)';
77 % define polygon in clockwise direction, and terminate
78 [Lat, Lon] = poly2ccw(coordMat(:,2),coordMat(:,1));
85 kmlStruct(ii).Geometry = geometry;
86 kmlStruct(ii).Name = name;
87 kmlStruct(ii).Description = desc;
88 kmlStruct(ii).Lon = Lon;
89 kmlStruct(ii).Lat = Lat;
90 kmlStruct(ii).BoundingBox = [[min(Lon) min(Lat);max(Lon) max(Lat)]];