In my django app I am using Geodjango, django-leaflet and leaflet-ajax. I have a route model with a LineStringField. I want to render that route in a template using a leaflet map. I have tried the following code with other models (those that have a Point field instead). But for any reason this code is not working with the RouteModel. The leaflet map shows nothing. How can I add that route to the "gis" leaflet map
Here is the model definition
from django.contrib.gis.db import models
class RouteModel(models.Model):
name = models.CharField(verbose_name=_("Nombre"), max_length=50, blank=False, null=False)
route_type_id = models.ForeignKey("RouteTypeModel", verbose_name=_("Tipo"),
blank=True, null=True, on_delete=models.SET_NULL,
related_name="routes")
start_date = models.DateField(verbose_name=_("Fecha inicio"))
end_date = models.DateField(verbose_name=_("Fecha fin"))
route_geom = models.LineStringField(verbose_name=_("Ruta"), srid=4326)
def __str__(self):
return self.name
class Meta:
db_table = 'riesgo_route'
managed = True
verbose_name = _('Ruta')
verbose_name_plural = _('Rutas')
Here is the ajax view:
@login_required(login_url='/login/')
def route_get_location(request,pk):
route=serialize('geojson',RouteModel.objects.filter(id=pk))
return HttpResponse(route,content_type='json')
urlpatterns = [
# url definitions
path('ruta/localizar/<str:pk>', route_get_location, name='route_locate'),
]
And in the template:
{% leaflet_map "gis" callback="window.our_layers" %}
<script type="text/javascript">
function our_layers(map,options){
//var datasets= new L.GeoJSON.AJAX("{% url 'mailapp:polygon_get_location' %}" ,{});
var datasets= new L.GeoJSON.AJAX("{% url 'riesgo:route_locate' route.id %}" ,{});
datasets.addTo(map);
}
</script>
I just found the Issue: I had a duplicate of the route_get_location function in another file. So the this post is a working example of how to represent a Geodjango model using django-leaflet and leaflet-ajax