欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 新车 > 实现uniapp天地图边界范围覆盖

实现uniapp天地图边界范围覆盖

2024/10/26 18:55:01 来源:https://blog.csdn.net/Enya61/article/details/143041107  浏览:    关键词:实现uniapp天地图边界范围覆盖

在uniapp中,难免会遇到使用地图展示的功能,但是百度谷歌这些收费的显然对于大部分开源节流的开发者是不愿意接受的,所以天地图则是最佳选择。 此篇文章,详细的实现地图展示功能,并且可以自定义容器宽高,还可以定向的进行行政区边界颜色划分。你可以根据代码运行并进一步稍微改下行政区编码即可实现自己想要的效果。

代码效果如下图所示:

示例代码:

<!DOCTYPE html>
<html lang="en"><head><script src="http://api.tianditu.gov.cn/api?v=4.0&tk=天地图的key"></script><style>body {margin: 0;padding: 0;overflow: hidden;height: 100vh;font-family: "Microsoft YaHei";}#viewDiv {width: 100%;height: 100%;position: absolute;top: 0;left: 0;}</style></head><body><div id="viewDiv"></div><script>function load() {// 初始化地图对象const map = new T.Map("viewDiv");addGeoBoundary(map);map.enableScrollWheelZoom();// 添加地图类型控件const ctrl = new T.Control.MapType();map.addControl(ctrl);map.setMapType(window.TMAP_NORMAL_MAP);// 添加比例尺控件const scale = new T.Control.Scale();map.addControl(scale);}function addGeoBoundary(map) {fetch('https://geo.datav.aliyun.com/areas_v3/bound/geojson?code=520322').then(response => response.json()).then(data => {const coordinates = data.features[0].geometry.coordinates;const centroid = data.features[0].properties.centroid;// 设置地图中心为该行政区域的质心map.centerAndZoom(new T.LngLat(centroid[0], centroid[1]), 8);coordinates.forEach(polygon => {polygon.forEach(boundary => {const boundaryPolygon = new T.Polygon(boundary.map(coord => new T.LngLat(coord[0], coord[1])), {color: "#7C7BF6",weight: 1,opacity: 0.7,fillColor: "#ABAAF3",fillOpacity: 0.1});boundaryPolygon.addEventListener("mouseover", () => {boundaryPolygon.setFillColor("#ABAAF3");boundaryPolygon.setFillOpacity(0.6);});boundaryPolygon.addEventListener("mouseout", () => {boundaryPolygon.setFillColor("#DCDBF0");boundaryPolygon.setFillOpacity(0.6);});map.addOverLay(boundaryPolygon);});});}).catch(error => console.error('Error fetching GeoJSON:', error));}load();</script></body>
</html>

然后再你需要展示展示地图的页面引入以下代码:

注意一定要使用iframe,不要使用web-view!!否则布局会变得很奇怪

<uni-section title="地区分布" class="item map-container" type="line"><iframe src="/static/skymap.html" class="map-frame"></iframe></uni-section></uni-section>

样式代码:

你也可以自定义实现自己想要的效果:

<style>.map-container {position: relative;}.map-frame {width: 100%;height: 500rpx;border: none;}
</style>

示例代码源自天地图:天地图API。至此地图即可以正确展示了。如果感觉还不错,点个关注收藏吧。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com