功能:
主要展示了Matlab读取 .tif(.tiff) 格式文件生成 geojson 文件的代码,包含:
- 读取tif文件(快速获取经纬度信息)
- 生成geojson文件 (类似格式文件皆可以)
任何类似(x,y,value)的数据均可以生成类似geojson格式的文件。
代码:
%% matlab——尝试读取tif文件信息并保存为json文件
clear,clc
%% info
filepath='MCS.tif';
savepath='point.geojson';
%% 读取文件
info = geotiffinfo(filepath);
readdata = readgeoraster(filepath);
%% 获取经纬度
xi = zeros(size(readdata));
yi = zeros(size(readdata));
for i = 1 : size(xi, 1)
xi(i, :) = i;
end
for j = 1 : size(yi, 2)
yi(:, j) = j;
end
[lat_Data,lon_Data]= pix2latlon(info.RefMatrix, xi, yi);
clear xi yi i j
%% 要保存的数据(数据量太多,geojson文件很大,这里指point格式)
len=1600;
lonlat=[lon_Data(1:len:end)',lat_Data(1:len:end)'];
savedata=readdata(1:len:end)';
%% 保存为geojson文件---------point
% 构建 GeoJSON
geojson = struct;
geojson.type = 'FeatureCollection';
for i = 1:size(lonlat,1)
geojson.features(i).type = 'Feature';
geojson.features(i).geometry.coordinates = lonlat(i,1:2);%坐标
geojson.features(i).properties = savedata(i); %属性值
geojson.features(i).geometry.type = 'Point';%Polygon
end
% 转换为 JSON 并保存
json = jsonencode(geojson);
fid = fopen(savepath,'w');
fwrite(fid, json);
fclose(fid);
注释:
Geojson格式文件的内容可以通过网站(geojson.io | powered by Mapbox)查看,例如:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {},
"geometry": {
"coordinates": [
105.16588104231431,
33.5047245491034
],
"type": "Point"
}
}
]
}
上述 Matlab 代码主要展示了 Point(点)类型数据的生成,如果是 Polygon(面)类型,数据格式如下。
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {},
"geometry": {
"coordinates": [
[
[
112.54869354231522,
28.844637418133914
],
[
118.3494747923142,
30.22106608006534
],
[
113.7791622923151,
35.389016216871454
],
[
112.54869354231522,
28.844637418133914
]
]
],
"type": "Polygon"
}
}
]
}
要生成 Polygon 格式数据仅需要修改 type 的内容,然后在 coordinates 中添加 Polygon 的边界点坐标即可。同一geojson文件中可包含多种类型数据
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {},
"geometry": {
"coordinates": [],
"type": "Polygon"
}
},
{
"type": "Feature",
"properties": {},
"geometry": {
"coordinates": [],
"type": "Point"
}
}
]
}
可以发现,该数据是以struct的形式处理并保存的,在实际应用中,根据所需文件格式,可自由调整 struct 中的变量名称及内容。