Leaflet: A JavaScript Library for Fitting Polylines in View

I spent some time playing with the Leaflet.js library to visualize running routes on a map. The goal was to zoom the map just enough to display the entire route drawn as a polyline. Leaflet makes this task straightforward, but I learned a valuable lesson while optimizing my initial solution.

In this article, I’ll walk you through how to use Leaflet.js to create a polyline for a running route and ensure that the map view adjusts perfectly to fit the polyline.

Pre-Requisites

Before we dive in, you’ll need to set up a basic HTML structure and include the necessary Leaflet.js files.

HTML Structure

code<div id="container">
<div id="map" style="width: 100%; height: 100%">
</div>
</div>

Required Libraries

Include the following JavaScript and CSS files to make use of Leaflet.js and additional features:

code<script src="http://cdn.leafletjs.com/leaflet-0.7/leaflet.js"></script>
<script type="text/javascript" src="https://rawgit.com/jieter/Leaflet.encoded/master/Polyline.encoded.js"></script>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7/leaflet.css"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.4.2/leaflet.draw.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.4.2/leaflet.draw.js"></script>

With the setup ready, let’s move on to creating the polyline.

Creating a Polyline for a Route

The polyline represents a segment of a running route that I often use. Here’s how you can create it:

JavaScript for Map Initialization and Polyline Creation

codevar map = L.map('map');
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 18 }).addTo(map);

var rawPoints = [
{ "latitude": 51.357874010145395, "longitude": -0.198045110923591 },
{ "latitude": 51.3573858289394, "longitude": -0.19787754933584795 },
{ "latitude": 51.35632791810057, "longitude": -0.19750254941422557 },
{ "latitude": 51.35553240304241, "longitude": -0.197232163894512 },
{ "latitude": 51.35496267279901, "longitude": -0.1970247338143316 },
{ "latitude": 51.35388700570004, "longitude": -0.19666483094752069 },
{ "latitude": 51.3533898352570, "longitude": -0.1964976504847828 },
{ "latitude": 51.35358452733139, "longitude": -0.19512563906602554 },
{ "latitude": 51.354762877995036, "longitude": -0.1945622934585907 },
{ "latitude": 51.355610110109986, "longitude": -0.19468697186046677 },
{ "latitude": 51.35680377680643, "longitude": -0.19395063336295112 },
{ "latitude": 51.356861596801075, "longitude": -0.1936180154828497 },
{ "latitude": 51.358487396611125, "longitude": -0.19349660642888197 }
];

var coordinates = rawPoints.map(rawPoint => new L.LatLng(rawPoint.latitude, rawPoint.longitude));

let polyline = L.polyline(coordinates, {
color: 'blue',
weight: 3,
opacity: 0.7,
lineJoin: 'round'
});

polyline.addTo(map);

This script initializes the map, creates a set of coordinates, and draws the polyline on the map.

Fitting the Map to the Polyline

Initially, I tried to calculate the center of the polyline and set the map view using the following code:

codelet lats = rawPoints.map(c => c.latitude).reduce((previous, current) => current += previous, 0.0);
let longs = rawPoints.map(c => c.longitude).reduce((previous, current) => current += previous, 0.0);

const position = [lats / rawPoints.length, longs / rawPoints.length];
map.setView(position, 17);

While this approach works for short polylines, it fails to account for the optimal zoom level for longer routes. After further research, I found a much simpler and more reliable solution.

The Optimal Solution: fitBounds

Leaflet provides a convenient method to automatically adjust the map view to fit a polyline or any other layer. Here’s the revised solution:

codemap.fitBounds(polyline.getBounds());

This single line of code uses the bounds of the polyline to set the map’s view, ensuring that the entire polyline is visible, regardless of its length or complexity.

Why Use fitBounds?

  • Ease of Use: One line of code handles all the calculations for you.
  • Accuracy: Ensures the polyline is perfectly framed within the map view.
  • Scalability: Works seamlessly with polylines of varying lengths and shapes.

Conclusion

Using fitBounds is a simple yet powerful way to adjust the map view to fit a polyline. Whether you’re working on a small project or a large-scale application, this method saves time and ensures accuracy. If you’re experimenting with Leaflet.js, I highly recommend exploring its extensive documentation and features.

Related blog posts