Java代码解析:将LINESTRING(经纬度)转换为多个LonLatVO对象

假设您有一个PostGIS数据库表geom_road_segment_t,其中包含名为geom的几何类型字段,该字段存储LINESTRING数据,例如LINESTRING(85.0445540574901 45.6184670972762,85.0151181532015 45.5612849795857)。您希望通过Java代码将查询到的LINESTRING数据解析为多个LonLatVO对象,每个LonLatVO对象代表一个经纬度坐标。

原始代码:

private List<LonLatVO> getSegLonLat(String id) {
    String sql = "SELECT ST_AsText(t.geom) FROM geom_road_segment_t t WHERE t.id = '" + id + "'";
    List<LonLatVO> result = primaryJdbcTemplate.query(sql, new RowMapper<LonLatVO>() {
        @Override
        public LonLatVO mapRow(ResultSet resultSet, int i) throws SQLException {
            String text = resultSet.getString("st_astext");
            String[] values = text.replaceAll("[A-Z\(\)]", "").split("\s+");
            LonLatVO lonLatVO = new LonLatVO();
            lonLatVO.setJd(values[0]);
            lonLatVO.setWd(values[1]);
            return lonLatVO;
        }
    });
    return result;
}

原始代码问题:

原始代码只能解析第一个经纬度坐标,而无法解析后续坐标。

解决方案:

修改代码如下:

private List<LonLatVO> getSegLonLat(String id) {
    String sql = "SELECT ST_AsText(t.geom) FROM geom_road_segment_t t WHERE t.id = '" + id + "'";
    List<LonLatVO> result = primaryJdbcTemplate.query(sql, new RowMapper<LonLatVO>() {
        @Override
        public LonLatVO mapRow(ResultSet resultSet, int i) throws SQLException {
            String text = resultSet.getString("st_astext");
            String[] values = text.replaceAll("[A-Z\(\)]", "").split(",");
            List<LonLatVO> lonLatVOList = new ArrayList<>();
            for (String value : values) {
                String[] lonLat = value.trim().split("\s+");
                LonLatVO lonLatVO = new LonLatVO();
                lonLatVO.setJd(lonLat[0]);
                lonLatVO.setWd(lonLat[1]);
                lonLatVOList.add(lonLatVO);
            }
            return lonLatVOList;
        }
    });
    return result;
}

代码解释:

  1. 使用split(",")将LINESTRING字符串拆分为多个经纬度坐标对。
  2. 使用循环遍历每个坐标对,并使用split("\s+")将其拆分为经度和纬度。
  3. 创建一个新的LonLatVO对象,并将经度和纬度分别设置为lonLat[0]lonLat[1]
  4. 将LonLatVO对象添加到lonLatVOList中。
  5. 返回lonLatVOList,它包含所有经纬度坐标的LonLatVO对象。

代码执行结果:

"locationList": [
    {
        "jd": "85.0445540574901",
        "wd": "45.6184670972762"
    },
    {
        "jd": "85.0151181532015",
        "wd": "45.5612849795857"
    }
]

注意:

  • 该代码假设LonLatVO类包含名为jdwd的属性,分别用于存储经度和纬度。
  • 您可以根据您的实际需求修改代码中的sql语句和LonLatVO类的属性名称。

通过以上代码修改,您可以成功将LINESTRING数据解析为多个LonLatVO对象,并获取每个经纬度坐标。


原文地址: https://www.cveoy.top/t/topic/p2iz 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录