首页 > 解决方案 > 我无法将几何图形转换为 openlayers 5.3 中 proj4.defs 中定义的投影

问题描述

我有一个使用 openlayers V5.3.0 的节点映射应用程序。当我尝试将几何图形从 EPSG:4326 转换为使用 proj4.defs 定义的投影时,我收到此错误消息:TypeError: Cannot read property 'getCode' of null

如果我将 openLayers 更改为 4.6.4 版,则转换几何图形的代码将起作用。

有没有其他人遇到过这个问题?

以下 HTML 演示了该问题。

<html>
<head>
    <meta http-equiv="Cache-Control" content="no-cache">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" >
    <title>Projection Test</title>

    <script
            src="https://code.jquery.com/jquery-2.2.4.min.js"
            integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
            crossorigin="anonymous"></script>

   <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/openlayers/4.6.4/ol-debug.js"></script> -->

    <script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.5.0/proj4.js"></script>


    <script>proj4.defs("EPSG:28355","+proj=utm +zone=55 +south +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs");</script>

     <script>

         $(document).ready(function() {
             let gJSONOpts = {
                 dataProjection: "EPSG:3857",
                 featureProjection: "EPSG:28355"
             };

             let jsonPt = {
                 "type": "Feature",
                 "id": "GEO_BRM_STOPS.fid--79f50be5_16adc4d0ce7_6a6b",
                 "geometry": {
                     "type": "Point",
                     "coordinates": [16154413.50099648, -4988654.4460995]
                 },
                 "geometry_name": "OBJ"
             };

             let feature = new ol.format.GeoJSON().readFeature(jsonPt.geometry, gJSONOpts);
             let tg = feature.getGeometry().transform('EPSG:28355', "EPSG:4326");
             let out = 'Projected Coordinates: ' + tg.getCoordinates()[0] + ', ' +tg.getCoordinates()[1];

             $("#mapvwr").html(out);

         });
     </script>
</head>
<body>
    <div id="mapvwr">

    </div>
</body>
</html>

将以上内容粘贴到 html 文件中并在浏览器中显示。

取消注释这一行:

 <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/openlayers/4.6.4/ol-debug.js"></script> -->

并注释掉以下行:

<script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>

要查看正确的结果:

Projected Coordinates: 145.11756553931886, -40.83921285742692

标签: javascriptopenlayers-5proj4js

解决方案


我发现了问题。ol.proj.proj4.register(proj4);定义投影后,我需要将其添加为脚本。


推荐阅读