首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Geodjango:如何加载.shp文件并使用正确的CRS转换为geojson?

Geodjango:如何加载.shp文件并使用正确的CRS转换为geojson?
EN

Stack Overflow用户
提问于 2020-06-19 09:06:26
回答 2查看 1.9K关注 0票数 4

我有多个shapefiles (.shp)和它们的辅助文件,我想要显示在传单地图上。shapefiles使用不同的坐标参考系统(CRS),我很难掌握在地图上显示事物的最直接、最可靠的方法。在geodjango教程中,DataSource用于加载shapefile并对其进行操作。但是,在它们的示例中,它们只检索单个特征的几何形状,而不是整个shapefile的几何形状。我使用了PyShp,并且能够使用以下内容显示地图:

代码语言:javascript
复制
    sf = shapefile.Reader(filename)
    shapes = sf.shapes()
    geojson = shapes.__geo_interface__
    geojson = json.dumps(geojson)

但是,当CRS不是WGS84时,这就失败了,而且我也不知道如何转换它。

阅读更多,这个职位抱怨CRS支持和pyshp,并建议使用ogr2ogr。

因此,在尝试理解这些选项之后,我认为使用Datasource、pyshp和ogr2ogr作为可能的选项,但我不知道哪个选项最有意义。

我想要的只是将一个使用Django的.shp文件转换成一个使用WGS84的geojson字符串,这样我就可以将它包含在一个使用传单.的HTML页面上。

有更多经验的人能提出一条特定的路线吗?

EN

回答 2

Stack Overflow用户

发布于 2020-06-25 12:14:14

使用Django的DataSource读取任何shapefile,然后将其转换为EPSG:4326 (aka WGS84),没有一种直接的方式,因此我们需要一步一步地创建,并解决当我们到达它们时出现的问题。

让我们开始这个过程:

  1. 创建需要读取的所有.shp文件路径的列表。应该是这样的: SHP_FILE_PATHS = 'full/path/to/shapefile_0.shp','full/path/to/shapefile_1.shp',.‘'full/path/to/shapefile_n.shp’
  2. DataSource将shapefile读入对象中。这些信息存储在对象的Layers中(表示一个多层的shapefile),该文件知道它们的srs是一个SpatialReference。这一点很重要,因为我们将在稍后将几何转换为WGS84 ,以便在地图上显示。
  3. 从每个shapefile的每一层中,我们将使用get_geoms()方法提取OGRGeometry srs感知对象的列表。
  4. 每个这样的几何都有一个json方法,该方法: 以JSON格式返回此几何图形的字符串表示:OGRGeometry(‘Point(12)’).json '{ "type":"Point",“坐标”:1.000000,2.000000 }‘

它非常有用,因为它是创建一个可在地图上显示的FeatureCollection 类型geojson的解决方案的一半。

  1. FeatureCollection geojson有一个非常特定的格式,因此我们将创建这个基础并按步骤填充它: feature_collection ={ 'type':'FeatureCollection','crs':{ 'type':'name','properties':{'name':'EPSG:4326' },'features':[}]
  2. 最后,我们需要以以下格式使用提取的几何图形填充features列表: {“类型”:“特征”,“几何”:{“类型”:Geometry_String,“坐标”:coord_list },“属性”:{“名称”:feature_name_string }

让我们把所有这些放在一起:

代码语言:javascript
复制
for shp_i, shp_path in enumerate(SHP_FILE_PATHS):
    ds = DataSource(shp_path)
    for n in range(ds.layer_count):
        layer = ds[n]
        # Transform the coordinates to epsg:4326
        features = map(lambda geom: geom.transform(4326, clone=True), layer.get_geoms())
        for feature_i, feature in enumerate(features):
            feature_collection['features'].append(
                {
                    'type': 'Feature',
                    'geometry': json.loads(feature.json),
                    'properties': {
                        'name': f'shapefile_{shp_i}_feature_{feature_i}'
                    }
                }
            )

现在,feature_collection dict将包含转换为epsg:4326的提取的特性集合,您可以从它创建一个json (例如。json.dump(feature_collection))

注意:虽然会工作,但它似乎有点适得其反,您可以考虑永久地将shapefiles读入模型中,而不是动态加载它们。

票数 4
EN

Stack Overflow用户

发布于 2021-03-11 06:44:54

代码语言:javascript
复制
#models.py

from __future__ import unicode_literals
from django.db import models
from django.contrib.gis.db import model
# county


class County(models.Model):
    district = models.CharField(max_length=50)
    count = models.FloatField()
    county_nam = models.CharField(max_length=50)
    code = models.BigIntegerField()
    geom = models.MultiPolygonField(srid=4326)

    def _unicode_(self):
        return self.county_nam

    class Meta:
        verbose_name_plural="County"

在望

代码语言:javascript
复制
from django.shortcuts import render
from django.views.generic import TemplateView
from django.core.serializers import serialize
from django.http import HttpResponse
from .models import County

# Create your views here.

class HomePageView(TemplateView):
    template_name='index.html'

# county views

def county_datasets(request):
    county=serialize('geojson',County.objects.all())
    return HttpResponse(county,content_type='application/json

在urls.py中

代码语言:javascript
复制
from django.conf.urls import url
from djgeojson.views import GeoJSONLayerView
from .views import HomePageView,county_datasets

# create your urls here


urlpatterns=[
    url(r'^$',HomePageView.as_view(),name='home'),
    url(r'^county_data/$',county_datasets,name='county'),

]

运行服务器

通过以下方式检查geojson数据

数据/

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62466883

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档