如何利用JavaScript读取shp文件,以及如何动态添加Echarts线条和点数据,渲染地图的线和点,适用于公交线路,管道线路等等

读取shp一般来说都是后台去做,但是现在不需要进行读取库的话,可以直接用前台做

代码如下:

    // 初始化地图读取本地的shp文件
        function readLocalData(pointData, lineData) {
            // 读取本地的 .shp 文件,主要是作为一个显示的参考,当查询 节点数据的时候,需要有一些shp线数据作为参考,但是不需要变化颜色
            shapefile.read('../json/shp/line_project.shp')
                .then(function (result) {
                    // 从解析结果中提取坐标信息数组
                    let geomData = result.features.map(feature => {

                        // console.log("feature=",feature)
                        const coordinates_start = feature.geometry.coordinates[0];
                        const coordinates_end = feature.geometry.coordinates[1];

                        //线wgs84转换成 火星坐标系
                        const gcj_start_lng = wgs84togcj02(coordinates_start[0], coordinates_start[coordinates_start.length - 1])[0]
                        const gcj_start_lat = wgs84togcj02(coordinates_start[0], coordinates_start[coordinates_start.length - 1])[1]


                        const gcj_end_lng = wgs84togcj02(coordinates_end[0], coordinates_end[coordinates_end.length - 1])[0]
                        const gcj_end_lat = wgs84togcj02(coordinates_end[0], coordinates_end[coordinates_end.length - 1])[1]


                        //然后再转换成百度坐标系
                        const baidu_start_lng = gcj02tobd09(gcj_start_lng, gcj_start_lat)[0]
                        const baidu_start_lat = gcj02tobd09(gcj_start_lng, gcj_start_lat)[1]

                        const baidu_end_lng = gcj02tobd09(gcj_end_lng, gcj_end_lat)[0]
                        const baidu_end_lat = gcj02tobd09(gcj_end_lng, gcj_end_lat)[1]


                        // console.log("baidu_start_lng=", baidu_start_lng)
                        // console.log("baidu_start_lat=", baidu_start_lat)
                        // console.log("baidu_end_lng=", baidu_end_lng)
                        // console.log("baidu_end_lat=", baidu_end_lat)

                        const start_x = baidu_start_lng;
                        const start_y = baidu_start_lat;

                        const end_x = baidu_end_lng;
                        const end_y = baidu_end_lat;
                        return {
                            // coords: [[start_x, start_y], [end_x, end_y]],//百度地图的坐标系
                            coords: [[gcj_start_lng, gcj_start_lat], [gcj_end_lng, gcj_end_lat]],//高德地图的坐标系
                        };
                    });

                    // 最终的数据格式   但是放在百度地图上有偏移,等后面转换成百度地图的坐标系


                    // console.log("读取出来的东西=",geomData)

                    if (lineData != null) {
                        //如果是点数据,就把点数据和线数据合并
                        console.log("lineData不为空,则把本地读取的shp线数据赋值到地图上用来配合点数据显示")
                        geomData = null;
                    }

// 使用百度地图的扩展加载高德地图
                    // 在创建地图图表之前,设置高德地图的风格
                    echarts.registerMap('amap', {
                        // style: 'dark' // 设置地图风格为黑色风格
                    });
                    // 创建地图图表
                    var mapChart = echarts.init(document.getElementById('mapChart'));

                    // 设置地图配置项
                    var mapOption = {
                        amap: {
                            center: [120.34591, 36.238],//地图中心点
                            zoom: 12,//变焦
                            roam: true,
                            minZoom: 9, // 最小缩放级别
                            maxZoom: 18, // 最大缩放级别
                            // tile: { //引用了apiv2.0.3.min.js  后,在其代码里设置瓦片地图的地址,这里不需要设置
                            //     x: 256,
                            //     y: 256,
                            //     url: 'F:/nginx_map/html/chengyangTiles/{z}/{x}/{y}.png'
                            // },

                            // 自定义地图加载方法
                            getTilesUrl: function (x, y, z) {
                                return 'YourLocalTilesPath/' + z + '/' + x + '/' + y + '.png';
                            },
                            // mapStyle: 'amap://styles/darkblue' // 设置地图风格为黑色风格
                        },
                        tooltip: {
                            trigger: 'item',
                            formatter: function (params, ticket, callback) {
                                if (params.data.value && params.data.value.length > 2) {
                                    return params.data.value[2];
                                } else {
                                    return params.data[2];
                                }
                            },
                        },
                        series: [
                            {
                                type: 'effectScatter',
                                coordinateSystem: 'amap',
                                data: pointData,//后端请求的点shp数据
                                itemStyle: {
                                    color: function (params) {
                                        var color = params.data[3];
                                        return color;
                                    },
                                    shadowBlur: 5,   // 阴影的模糊程度
                                    shadowColor: '#333'   // 阴影的颜色
                                },
                                symbolSize: 7,  // 调整点的直径大小
                                showEffectOn: 'emphasis',   // 特效显示的时机为高亮状态
                                rippleEffect: {   // 涟漪特效设置
                                    brushType: 'stroke',   // 设置涟漪特效的画笔类型为描边
                                    period: 10, // 设置涟漪的周期,数值越小涟漪越频繁
                                    scale: 30, // 设置涟漪的大小,数值越大涟漪越大
                                },
                                hoverAnimation: true,   // 鼠标悬停时是否启用动画效果
                                // label: {   // 标签设置
                                //     formatter: '{b}',   // 标签内容格式化
                                //     position: 'right',   // 标签位置在图形的右侧
                                //     show: true   // 是否显示标签
                                // },
                                zlevel: 1   // 系列的层级,用于控制图形的覆盖顺序

                            },
                            // {
                            //     type: 'lines', //绘制线条   没用,保留主要是为了看json数据格式
                            //     coordinateSystem: 'amap',
                            //     polyline: true,
                            //     data: [
                            //         {
                            //             coords: [
                            //                 [120.20372, 36.34189],
                            //                 [120.34271, 36.23179],
                            //             ],
                            //             value: ['featid', 'fanciyu', '目标线条', 'red'],
                            //         },
                            //         {
                            //             coords: [
                            //                 [120.2035, 36.3439],
                            //                 [120.34271, 36.23179],
                            //             ],
                            //             value: [120.20372, 36.34189, '目标线条2', 'blue'],
                            //         }
                            //
                            //     ],
                            //     lineStyle: {
                            //         color: 'black',
                            //         width: 1  // 调整线的粗细
                            //     },
                            // },


                        ],

                    };


                    // 动态添加 lines 对象,如果传入线shp数据,才进行添加
                    if (lineData) {
                        lineData.forEach(function (data) {
                            console.log("当lineData存在时候,进入方法输出data=", data)
                            if (data) {
                                var lines = {
                                    type: 'lines',
                                    coordinateSystem: 'amap',
                                    polyline: true,
                                    data: data.lineShpVOList,
                                    lineStyle: {
                                        color: data.color,
                                        width: 3,  // 调整线的粗细
                                        // type: 'dashed' // 设置线条为虚线,这样设置可以显示出流动效果,不然太粗的线没有流动效果
                                    },
                                    // effect: {
                                    //     constantSpeed: 20,   // 设置运动的速度为20
                                    //     show: true,         // 设置显示效果为true
                                    //     trailLength: 0.1,   // 设置尾迹的长度为线条长度的10%
                                    //     symbolSize: 1.5     // 设置符号的大小为1.5
                                    // },
                                    zlevel: 2  // 设置元素的层级为1
                                };
                                mapOption.series.push(lines);//此option是其他对象的option
                            }
                        });
                    } else {//如果没有传入线shp数据,就使用默认的线shp数据,作为点的搭配
                        var lines = {
                            type: 'lines',
                            coordinateSystem: 'amap',
                            polyline: true,
                            data: geomData,//本地数据渲染的线shp数据
                            lineStyle: {
                                color: 'rgb(0,0,0)',
                                width: 1,  // 调整线的粗细
                            },
                            // effect: {
                            //     constantSpeed: 20,   // 设置运动的速度为20
                            //     show: false,         // 设置显示效果为true
                            //     trailLength: 0.1,   // 设置尾迹的长度为线条长度的10%
                            //     symbolSize: 1.5     // 设置符号的大小为1.5
                            // },
                            zlevel: 10  // 设置元素的层级为1
                        };

                        mapOption.series.push(lines);//此option是其他对象的option
                        console.log("进入方法B")

                    }

// 使用加载本地瓦片地图数据的插件
                    // 加载 echarts-amap 插件和 Leaflet
                    // echarts.registerMap('amap', {});
                    // echarts.initAMap();


                    // 在这里调用 mapChart.setOption(option)  更新地图,否则不会显示
                    mapChart.setOption(mapOption);

                    //在线的地图才能用这段代码
                    // var bmap = mapChart.getModel().getComponent('bmap').getBMap()
                    // bmap.addControl(new BMap.MapTypeControl({mapTypes: [BMAP_NORMAL_MAP, BMAP_SATELLITE_MAP, BMAP_HYBRID_MAP]}));
                    // bmap.setMapStyle({style: 'normal'})

                    // drawBoundaryOnMap();//添加本地json边界到地图,先注释掉,后期需要再打开

                })
            // .catch(function (error) {
            //     showAlert('本地shp数据读取失败', 'error', 3000);
            // });
        }


        //添加本地json边界到地图,暂时先不用
        function drawBoundaryOnMap() {
            fetch('../json/青岛市城阳区.json')
                .then((response) => response.json())
                .then((data) => {
                    var mapChart = echarts.getInstanceByDom(document.getElementById('mapChart')); // 找到已有对象

                    var datajson = data.coordinates[0][0];

                    console.log("查询的数据=", datajson);

                    var geomData = [];

                    for (var i = 0; i < datajson.length - 1; i++) {
                        var start_lng = datajson[i][0];
                        var start_lat = datajson[i][1];
                        var gcj_lng = wgs84togcj02(start_lng, start_lat)[0];
                        var gcj_lat = wgs84togcj02(start_lng, start_lat)[1];

                        var baidu_lng = gcj02tobd09(gcj_lng, gcj_lat)[0];
                        var baidu_lat = gcj02tobd09(gcj_lng, gcj_lat)[1];

                        // geomData.push([baidu_lng, baidu_lat]);//百度地图坐标
                        geomData.push([gcj_lng, gcj_lat]);//国测局坐标
                    }

                    var newSeries = [
                        {
                            type: 'lines',
                            coordinateSystem: 'amap',//百度用bmap,高德用amap
                            polyline: true,
                            data: [{
                                coords: geomData,
                                value: ['xxxx', 'xxxx', '青岛市城阳区边界', 'red'],
                            }],
                            lineStyle: {
                                color: 'red',
                                width: 1
                            },
                        },
                    ];

                    var originalOption = mapChart.getOption();
                    var originalSeries = originalOption.series || [];

                    var mergedSeries = originalSeries.concat(newSeries);

                    var mapOption = {
                        series: mergedSeries,
                    };

                    mapChart.setOption(mapOption);
                    console.log('地图加载完成');
                })
                .catch((error) => {
                    console.error('读取JSON文件失败:', error);
                });
        }

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
和面元素,具体实现方法如下: 1. 安装需要的 Python 库,包括:geopandas、matplotlib 和 descartes。 2. 使用 geopandas 读取本地的 shp 文件,得到一个 GeoDataFrame 对象。例如: ``` import geopandas as gpd map_df = gpd.read_file('path/to/your/shpfile.shp') ``` 3. 使用 matplotlib 创建一个画布,并将地图数据绘制在画布上。例如: ``` import matplotlib.pyplot as plt fig, ax = plt.subplots() map_df.plot(ax=ax) ``` 4. 使用 matplotlib 的交互模式,使得地图能够滚轮缩放。例如: ``` plt.axis('equal') plt.axis('off') plt.tight_layout() plt.show(block=False) plt.rcParams['toolbar'] = 'toolmanager' toolmanager = plt.get_current_fig_manager().toolbar toolmanager.add_tool('Zoom', 'mpl_toolkits.toolbar.icons.Zoom', 'Zoom') toolmanager.add_tool('Pan', 'mpl_toolkits.toolbar.icons.Pan', 'Pan') ``` 5. 添加元素。首先,创建一个包含坐标和属性的 Pandas DataFrame 对象。然后,将 DataFrame 转换为 GeoDataFrame 对象,并将其绘制在地图上。例如: ``` import pandas as pd points = pd.DataFrame({ 'Name': ['Point 1', 'Point 2', 'Point 3'], 'Latitude': [38.8951, 38.8904, 38.8887], 'Longitude': [-77.0364, -77.0320, -77.0321] }) from shapely.geometry import Point geometry = [Point(xy) for xy in zip(points.Longitude, points.Latitude)] points_gdf = gpd.GeoDataFrame(points, geometry=geometry) points_gdf.plot(ax=ax, color='red', markersize=10) ``` 6. 绘制线和面元素。首先,创建一个包含线或面的几何对象和属性的 GeoDataFrame 对象。然后,将其绘制在地图上。例如: ``` from shapely.geometry import LineString, Polygon lines = gpd.GeoDataFrame({ 'Name': ['Line 1'], 'geometry': [LineString([(0, 0), (1, 1)])] }) lines.plot(ax=ax, color='green') polygons = gpd.GeoDataFrame({ 'Name': ['Polygon 1'], 'geometry': [Polygon([(0, 0), (1, 1), (1, 0)])] }) polygons.plot(ax=ax, color='blue', alpha=0.5) ``` 完整代码示例: ``` import geopandas as gpd import matplotlib.pyplot as plt import pandas as pd from shapely.geometry import Point, LineString, Polygon # 读取地图数据 map_df = gpd.read_file('path/to/your/shpfile.shp') # 创建画布 fig, ax = plt.subplots() # 绘制地图 map_df.plot(ax=ax) # 滚轮缩放 plt.axis('equal') plt.axis('off') plt.tight_layout() plt.show(block=False) plt.rcParams['toolbar'] = 'toolmanager' toolmanager = plt.get_current_fig_manager().toolbar toolmanager.add_tool('Zoom', 'mpl_toolkits.toolbar.icons.Zoom', 'Zoom') toolmanager.add_tool('Pan', 'mpl_toolkits.toolbar.icons.Pan', 'Pan') # 添加元素 points = pd.DataFrame({ 'Name': ['Point 1', 'Point 2', 'Point 3'], 'Latitude': [38.8951, 38.8904, 38.8887], 'Longitude': [-77.0364, -77.0320, -77.0321] }) geometry = [Point(xy) for xy in zip(points.Longitude, points.Latitude)] points_gdf = gpd.GeoDataFrame(points, geometry=geometry) points_gdf.plot(ax=ax, color='red', markersize=10) # 绘制线和面元素 lines = gpd.GeoDataFrame({ 'Name': ['Line 1'], 'geometry': [LineString([(0, 0), (1, 1)])] }) lines.plot(ax=ax, color='green') polygons = gpd.GeoDataFrame({ 'Name': ['Polygon 1'], 'geometry': [Polygon([(0, 0), (1, 1), (1, 0)])] }) polygons.plot(ax=ax, color='blue', alpha=0.5) # 显示画布 plt.show() ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值