Search code examples
djangoleafletgeodjangodjango-leaflet

How to set bounds to django leaflet map?


In my django app I have a CenterModel with a location (Point) field and a RouteModel with a geom (Linestring) field. I am using django-leaflet to represent those geometric fields in the views (UI). I can represent those fields, but in the general settings I had set the default center and zoom for every leaflet map, so when i represent the center or the route I have to zoom out amd move the map to see the marker and the line, Is there any way to set the bounding box of the map to see the point or the line without having to zoom out and move the map?

The point is represented outside this area and I have to zoom out The point is represented outside this area and I have to zoom out I have try with:

map.setBounds(datasets.getBounds());

but it shows the error that the setBounds method does not exist

Here is my code:

This is how I represent the route: In the template:

<div class="row">
 {% leaflet_map "gis" callback="window.our_layers" %}                        
</div>

<script type="text/javascript">
    function our_layers(map,options){
        var datasets= new L.GeoJSON.AJAX("{% url 'riesgo:route_locate' route.id %}" ,{});
        
        datasets.addTo(map);        
        // this is showing an error       
        map.setBounds(datasets.getBounds());
    }                              
</script>

#the ajax views

@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')

representing the center in other template

<div class="row">
   {% leaflet_map "gis" callback="window.our_layers" %}
</div>

<script type="text/javascript">
    function our_layers(map,options){
        var datasets= new L.GeoJSON.AJAX("{% url 'riesgo:center_locate' center.id %}" ,{});
        datasets.addTo(map);  
        map.setBounds(datasets.getBounds());  
    }                                  
</script>

the ajax view to get the center

@login_required(login_url='/login/')
def center_get_location(request,pk):
    center=serialize('geojson',CenterModel.objects.filter(id=pk))
    return HttpResponse(center,content_type='json')

settings:

LEAFLET_CONFIG = {
  'DEFAULT_CENTER': (18.47186, -69.89232),
  'DEFAULT_ZOOM': 12,
  'MIN_ZOOM': 7,
  'MAX_ZOOM': 19,
  'RESET_VIEW' : False,
}

Solution

  • Try fitBounds instead of setBounds.

    map.fitBounds(datasets.getBounds());
    

    Related question