amaurs
amaurs

Reputation: 1642

Bounding box in mapbox.js

I have a spatial database with thousands of polygons distributed across a country. I want to display those polygons in a mapbox or a leaflet map. However, a simple query that retrieves all of the objects in the database is a massive load for the network and takes a long time, and when it finally loads it takes much of the RAM just holding the geojson object.

I want to solve this more intelligently by querying only the objects that fall within the current map viewport. To this end, I modified my REST service to receive a polygon and using it to filter the queryset (I am using Django REST). This is already working, what I can't figure out is how to obtain the extent of the current viewport.

Does mapbox.js expose this functionality? How can I solve this?

By the way, I am using mapbox.js instead of mapboxgl only because of omnivore support as I am using the well known text format. I am in an early development stage so if this is easier to solve with another library I am open to considering it.

Upvotes: 2

Views: 2375

Answers (1)

ghybs
ghybs

Reputation: 53370

As you may have noticed, mapbox.js extends Leaflet.

Therefore you should be able to use the map.getBounds() method to retrieve the extent of the current viewport.

Returns the geographical bounds visible in the current map view

Typically you would listen to the "moveend" event and perform your query.

Fired when the center of the map stops changing (e.g. user stopped dragging the map).

Example:

var map = L.map('map').setView([48.86, 2.35], 11);

map.on('moveend', function() {
  console.log(map.getBounds().toBBoxString());
});

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ==" crossorigin="" />
<script src="https://unpkg.com/[email protected]/dist/leaflet-src.js" integrity="sha512-IkGU/uDhB9u9F8k+2OsA6XXoowIhOuQL1NTgNZHY1nkURnqEGlDZq3GsfmdJdKFe1k1zOc6YU2K7qY+hF9AodA==" crossorigin=""></script>

<div id="map" style="height: 200px"></div>

Upvotes: 1

Related Questions