【问题标题】:Show geojson featureCollection with Leaflet使用 Leaflet 显示 geojson featureCollection
【发布时间】:2017-12-02 15:49:48
【问题描述】:

使用 QGIS,我已将多边形图层导出为 geojson,我想将其与传单一起发布。这就是 geojson 的样子 [由于 SO 字符限制而被排除]: https://gist.github.com/t-book/88806d12d7f05024b147715be82e6844

这是我尝试过的:

将 geojson 包装为 var:

var states = [{
    "type": "FeatureCollection",
    "crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:EPSG::31468" } },
    "features": [
       { "type": "Feature", "properties": ...
}];

作为新层添加:

L.geoJSON(states, {
    style: function(feature) {
        switch (feature.properties.party) {
            case 'Euerbach': return {color: "#ff0000"};
            case 'Werneck':   return {color: "#0000ff"};
        }
    }
}).addTo(map);

不幸的是,没有渲染任何内容。如何正确将此 geojson featureCollection 添加到我的地图?

【问题讨论】:

    标签: leaflet geojson map-projections


    【解决方案1】:

    问题在于您的数据是投影的 - Leaflet 期望您的数据是未投影的(由长/纬度对组成,或在 WGS84/EPSG 4326 中“投影”)。有几个解决方案,这里想到了两个:

    • 在 QGIS 中,导出您的数据,使其由长/纬度坐标对组成

    • 在显示 geojson 时使用 proj4.js 重新投影您的坐标。

    对于第二个,您需要在将 geojson 添加为图层时设置 coordsToLatLng 选项:

    var geojson = L.geoJSON(states, {
        coordsToLatLng: function (p) {  
            // return get lat/lng point here.
    })
    

    此函数的主体将获取 geojson 坐标参考系统 (CRS) 中的坐标,并使用 proj4 在 WGS84 中返回它。

    此外,coordsToLatLng 函数希望您返回纬度/经度对。由于您的 geojson 和 proj4 代表 [x,y] 的数据,我们需要在返回新点之前交换我们的值。

    这可能看起来像:

    var geojson = L.geoJSON(states, {
        coordsToLatLng: function (p) {
            p = proj4(fromProjection,toProjection,p);  // reproject each point
            p = [p[1],p[0]]    // swap the values
            return p;          // return the lat/lng pair
        }
    }).addTo(map);
    

    当然,我们需要定义我们的 CRS。我在 spatialreference.org 上查找了您的 CRS(它在 geojson 本身中指定),并使用为该 CRS 和 EPSG4326 (WGS84) 提供的描述来设置我的 fromProjection 和 toPojection:

    var fromProjection = '+proj=tmerc +lat_0=0 +lon_0=12 +k=1 +x_0=4500000 +y_0=0 +ellps=bessel +datum=potsdam +units=m +no_defs ';
    var toProjection = "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs ";
    

    总而言之,这给了我们一些东西like this。 请记住,如果您有大文件,在 javascript 中重新投影它们将比在正确的 CRS 中导出它们花费更长的时间。

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-11
    • 1970-01-01
    • 1970-01-01
    • 2020-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多