2014-01-08 2 views
3

저는 최근에 GeoDjango를 사용하는 법을 배웠습니다. 모든 튜토리얼을 통해 모든 것이 어떻게 조합되는지 이해하려고 노력하고 있습니다. 나는 또한 GIS를 처음 사용하지만 비교적 편안하다.GeoDjango queryset 객체

내가 특별히 오래된 아닌 비트가있는 경우 중대하다이 튜토리얼을 따라 다음과 같은되었습니다 내가 할 수있는 장고 물건을 업데이트 https://code.google.com/p/geodjango-basic-apps/wiki/FOSS4GWorkshop

내가 제 8 항에 만든 또한 사용되지 않는 해결하기 위해 노력 OpenLayers 물건들,하지만 벽에 뭔가 쳤습니다.

튜토리얼은 검색어 세트를 생성하고이 OpenLayers.js에 의해 소비되는 템플릿을 보낼 수있는 다음과 같은 코드가 있습니다

튜토리얼의 view.py :

def ward(request, id): 
    ward = get_object_or_404(Ward, pk=id) 
    interesting_points = InterestingLocation.objects.filter(
      geometry__intersects=(ward.geometry)) 
    return render_to_response("ward.html", { 
     'ward': ward, 'interesting_points': interesting_points }) 

튜토리얼의 OpenLayers를 코드 (불완전) : 나는 followi를 작성했습니다

geojson_format = new OpenLayers.Format.GeoJSON() 
    ward = geojson_format.read({{ ward.geometry.geojson|safe}})[0]; 
    // We mark it 'safe' so that Django doesn't escape the quotes. 

    ward.attributes = { 'name': "{{ward.name}}", 'type': 'ward'}; 
    vectors = new OpenLayers.Layer.Vector("Data"); 
    vectors.addFeatures(ward); 

코드가 있지만 오류 메시지 (js 콘솔)가 계속 나타납니다. "개체가 ''대체 ''메서드가 아닙니다. 내 openlayers.js이

function map_init() { 
     json_format = new OpenLayers.Format.GeoJSON(); 
     countryson = json_format.read({{country.mpoly.geojson|safe}})[0]; 
     countryson.attributes = {'name': "{{country.name}}", 
          'area': "{{country.area}}", 
          'population': "{{country.pop2005}}", 
          'type': 'country'}; 
     vectors = new OpenLayers.Layer.Vector("Data"); 
     vectors.addFeatures(countryson); 
     var map = new OpenLayers.Map('map-container'); 
     var base_layer = new OpenLayers.Layer.OSM("Base Map", { 
       "tileOptions": { "crossOriginKeyword": null } 
     }); 
     map.addLayers([base_layer, vectors]); 
     map.zoomToMaxExtent(countryson.geometry.getBounds()); 
    } 

나는 오류가 줄을 믿습니다을 시도

def interesting_area(request, iso3_id): 
    iso3_id = iso3_id.upper() 
    country = get_object_or_404(WorldBorder, iso3=iso3_id) 
    interesting_points = InterestingLocation.objects.filter(
     geometry__intersects=(country.mpoly)) 
    return render_to_response("some_places.html", { 
     'country': country, 
     'interesting_points': interesting_points}) 

내 view.py countryson = json_format.read({{country.mpoly.geojson|safe}})[0];

사람은을 보내는 방법을 알고 있나요 모델 객체와 geometry.geojson 속성을 템플릿 측에서 읽을 수 있습니까? 이미 정적 파일을 반환하는 view/url을 사용하여이 작업을 수행하는 방법을 보았습니다.하지만이 작업을 수행하려면 템플릿에 데이터를 직접 반환해야합니다.

각주 : vectorformats 사용에 대한 몇 가지 다른 답변을 보았습니다. 그러나 GeoDjango에서 기본적으로이 작업을 수행 할 수있는 방법이 있어야하지만 Google 검색 및 응답 검색에서 찾을 수없는 것 같습니다. 사람들이 보통 이렇게하는 방법.

도움 주셔서 감사합니다.

편집 :

내가 조금 바보 느끼지만, @의 sk1p은 JS의 역 추적에 대해 나에게 물었다 나는 그것을 보았을 때, 그것은 오류에 대한 책임이있는 줄을 하더군요 다음

map.zoomToMaxExtent(countryson.geometry.getBounds()); 

그래서 제거하고 오류가 사라지지만 여전히 렌더링 할지도를 얻을 수 없습니다. 나는 반환 된 객체를 계속 살펴볼 것이다.

+0

질문/문제가 정확히 무엇입니까? – sk1p

+0

'입력'키를 눌러 신속하게 게시 할 수 있습니다. 완전한 질문으로 편집. – erewok

+0

js 오류에 대한 추적을 얻을 수 있습니까? 또한 생성 된 html/js : IIRC'.geojson'에서 전체 GeoJSON 객체를 반환하지 않는다면 OpenLayers API를보고 전달중인 내용을 받아 들일 수 있습니다. – sk1p

답변

3

많은 실험을 거친 후 서식 파일에 geojson을 렌더링하는 시스템을 발견했습니다. 내 오류가 아주 초등학교라고 생각하고 실제 지오메트리 필드 자체를 geojson으로 렌더링해야한다는 것을 이해하지 못해서 생긴 것입니다 (템플릿에서 액세스 할 수 있습니다).

리 폴렛을 사용하기로 전환했는데 실제로로드가 잘되었고 좋은 API를 갖고있는 것 같습니다.

셰이프 파일을 가져 와서 Shapefile-> Features-> Attributes로 나누는 프로그램이 있습니다. 이것은 Python for Geo-Spatial Development에 의해 영감을 얻었습니다. 관련 모델은 다음과 같습니다

이 models.py :

class Shapefile(models.Model): 
    filename = models.CharField(max_length=255) 
    srs_wkt = models.TextField() 
    geom_type = models.CharField(max_length=50) 

class Feature(models.Model): 
    shapefile = models.ForeignKey(Shapefile) 
    reference = models.CharField(max_length=100, blank=True) 
    geom_point = models.PointField(srid=4326, blank=True, null=True) 
    geom_multipoint = models.MultiPointField(srid=4326, blank=True, 
              null=True) 
    geom_multilinestring = models.MultiLineStringField(srid=4326, 
                 blank=True, 
                 null=True) 
    geom_multipolygon = models.MultiPolygonField(srid=4326, 
               blank=True, 
               null=True) 
    geom_geometrycollection = models.GeometryCollectionField(srid=4326, 
                  blank=True, 
                  null=True) 
    objects = models.GeoManager() 

    def __str__(self): 
     return "{}".format(self.id) 

    ## need some method to return the geometry type this guy has. 
    def _get_geometry(self): 
     geoms = [self.geom_point, self.geom_multipoint, 
       self.geom_multilinestring, self.geom_multipolygon, 
       self.geom_geometrycollection] 
     geom = next(filter(lambda x: x, geoms)) 
     return geom 

    geometry = property(_get_geometry) 

: 나는 일반적인 shape 파일을 처리하고 있는데 이전에 특징이있을 것이다 형상의 종류를 모르기 때문에, 내가 포함했다 geometry 실제 지오메트리 필드를 반환하고 사용되지 않는 다른 것들을 버리는 기능이 있습니다. 나중에이 템플릿을 사용하여 템플릿 내에서 지오메트리의 geojson 메서드에 액세스합니다.

필자는 필자가 셰이프 파일에있는 기능에 대한 쿼리와 함께 셰이프 파일 ID를 포함하는 요청에 응답합니다.

views.py :

def view_shapefile(request, shapefile_id, 
       template_file='shape_editor/viewshapefile.html'): 
    all_features = Feature.objects.filter(
        shapefile__id=shapefile_id).select_related(
          'shapefile') 
    filename = all_features[0].shapefile.filename 

    ### we need something to set the center of our map ### 
    lon, lat = all_features[0].geometry.centroid.tuple 
    temp_vars = {'features' : all_features, 
       'filename' : filename, 
       'lon': lon, 
       'lat' : lat} 
    return render(request, template_file, temp_vars) 

그리고 내 템플릿과 같이 반환 된 개체를 처리하는 리플릿을 사용

function map_init(map_div) { 
    var tileMapQuest = L.tileLayer('http://{s}.mqcdn.com/tiles/1.0.0/map/{z}/{x}/{y}.png', { 
subdomains: ['otile1','otile2','otile3','otile4'], 
attribution: 'Map tiles by <a href="http://open.mapquestapi.com/">MapQuest</a>. Data &copy; by <a href="http://www.openstreetmap.org/copyright">OpenStreetMap contributors</a>.', 
maxZoom: 18 
    }); 
    var map_layers = [tileMapQuest]; 
    var map = L.map('map-container', { 
    center: [{{ lat }}, {{ lon }}], 
    zoom: 10, 
    layers: map_layers, 
    worldCopyJump: false 
    }); 
    {% if features %} 
    {% for feat in features %} 
     var feature = new L.geoJson({{ feat.geometry.geojson|safe }}).addTo(map); 
    {% endfor %} 
    {% endif %} 
} 

나는 확실하지 않다 즉이 다른 누군가를 위해 도움이 될 것이다 경우 특히지도를 중앙에 배치하는 데 사용할 위도와 경도를 알아 내려고 할 때 더 나은 방법입니다.