makinacorpus / django-leaflet

Use Leaflet in your Django projects
GNU Lesser General Public License v3.0
716 stars 282 forks source link

Add a polygon to the leaflet map #211

Open h4k1m0u opened 6 years ago

h4k1m0u commented 6 years ago

Hi,

Is it possible to add a GeoDjango PolygonField to the Leaflet map? I've tried to do that by adding the js code below to my template, but I get a TypeError: t is null instead:

<script type="text/javascript">
    function map_init(map, options) {
        // zoom to point
        map.setView([51.9923, -2.1580], 12);

        // get polygon
        var polygon = "{{ extent.geometry.geojson }}";
        var polygon = L.polygon(polygon).addTo(map);
    }
</script>

In the code above extent is my object and the PolygonField is called geometry. So I thought maybe I should use the coords property instead. But the same error persisted.

mikahoy045 commented 6 years ago

Yes it's possible. Step that I did was :

  1. Set your geodjango polygon field to serialize via url: in view :
    def yourpolygon_datasets(request):
    yourpolygon = serialize('geojson', Yourpolygonmodel.objects.all())
    return HttpResponse(smpsungai, content_type='json')

in url: path('yourmodel_data/', yourmodel_datasets, name='yourmodelurl'),

You should be able to accessing it via host:port/yourmodelurl

  1. Set in your index so leaflet read the geojson
    var datasets_yourmodel = new L.GeoJSON.AJAX("{% url 'yourmodelurl' %}",{
           //query popup or color of polygon here
        }).addTo(map)