天地图Api4.0.怎么根据geojson的数据。把一个省的所有市区标记色块和文字
geojson数据下载地址:天地图 服务中心
实现效果:
我下载的是河南省-市的geojson数据
我这里标记文字内容的时候利用的turf插件计算的。
<!DOCTYPE html> <html> <head><meta http-equiv="content-type" content="text/html; charset=utf-8"/><title>天地图</title><script type="text/javascript" src="http://api.tianditu.gov.cn/api?v=4.0&tk=换成你自己的key值。没有的要去申请"></script><script src="https://cdn.jsdelivr.net/npm/@turf/turf@6.5.0/turf.min.js"></script><style type="text/css">body, html {width: 100%;height: 100%;margin: 0;font-family: "微软雅黑";}#mapDiv {height: 800px;width: 1200px;}input, p {margin-top: 10px;margin-left: 5px;font-size: 14px;}</style><script>var map, marker, label;var zoom = 8;async function onLoad() {//初始化地图对象map = new T.Map("mapDiv");//设置显示地图的中心点和级别map.centerAndZoom(new T.LngLat(113.55,33.88), zoom);//创建标注对象// var marker1 = new T.Marker(new T.LngLat(113.26357, 35.21241));// //向地图上添加标注// map.addOverLay(marker1);let cityGeoJSON =await loadGeoJSON('src/assets/json/henanCityGeoJSON.geojson');cityGeoJSON.features.forEach((feature,index) => {const { properties, geometry } = feature;const areaName = properties.name || `区域${index + 1}`; // 区域名称// 使用Turf.js计算质心和区域计算中心坐标并添加名称标注const centroid = turf.centroid(feature);const center = new T.LngLat(centroid.geometry.coordinates[0],centroid.geometry.coordinates[1]);const center1 = `${center.lng},${center.lat}`;const label = new T.Label({position: center,text: `<b>${areaName}</b>`,offset: new T.Point(-30, -30)});map.addOverLay(label);let polygon = createPolygonFromGeoJSON(feature);// 设置样式polygon.setStyle({color: "#000000",weight: 2,fillColor:getAreaColor(index),fillOpacity: 0.5,stroke: false});map.addOverLay(polygon);});}async function loadGeoJSON(path){const response = await fetch(path); return response.json();}// 从GeoJSON创建多边形function createPolygonFromGeoJSON(feature) {var coordinates = feature.geometry.coordinates;if (feature.geometry.type === "Polygon") {// 单多边形var paths = coordinates[0].map(coord => new T.LngLat(coord[0], coord[1]));return new T.Polygon(paths, {});} else if (feature.geometry.type === "MultiPolygon") {// 多多边形 - 天地图API需要将每个多边形单独创建后合并var paths = [];coordinates.forEach(polygon => {paths.push(polygon[0].map(coord => new T.LngLat(coord[0], coord[1])));});return new T.Polygon(paths, {});}}// 生成区域颜色(按索引循环使用预设颜色)const getAreaColor = (index) => {// 预设颜色列表(可根据需求扩展)const colors = ['#4285F4', '#EA4335', '#FBBC05', '#34A853','#9C27B0', '#FF9800', '#00BCD4', '#795548'];return colors[index % colors.length]; // 循环使用颜色};</script> </head> <body onLoad="onLoad()"> <div id="mapDiv"></div></body> </html>