rust 59 lines · 7 steps

Building geographic bounding boxes in Rust

A small value-type library that computes, pads, and centers a lat/lng bounding box over a set of points.

Explained by highlit
1use std::f64::consts::PI;
2 
3#[derive(Debug, Clone, Copy)]
4pub struct LatLng {
5 pub lat: f64,
6 pub lng: f64,
7}
8 
9#[derive(Debug, Clone, Copy)]
10pub struct BoundingBox {
11 pub south_west: LatLng,
12 pub north_east: LatLng,
13}
14 
15impl BoundingBox {
16 pub fn from_points(points: &[LatLng]) -> Option<Self> {
17 let first = points.first()?;
18 let mut min_lat = first.lat;
19 let mut max_lat = first.lat;
20 let mut min_lng = first.lng;
21 let mut max_lng = first.lng;
22 
23 for p in &points[1..] {
24 min_lat = min_lat.min(p.lat);
25 max_lat = max_lat.max(p.lat);
26 min_lng = min_lng.min(p.lng);
27 max_lng = max_lng.max(p.lng);
28 }
29 
30 Some(BoundingBox {
31 south_west: LatLng { lat: min_lat, lng: min_lng },
32 north_east: LatLng { lat: max_lat, lng: max_lng },
33 })
34 }
35 
36 pub fn padded(&self, meters: f64) -> Self {
37 let lat_delta = meters / 111_320.0;
38 let mid_lat = (self.south_west.lat + self.north_east.lat) / 2.0;
39 let lng_delta = meters / (111_320.0 * (mid_lat * PI / 180.0).cos());
40 
41 BoundingBox {
42 south_west: LatLng {
43 lat: self.south_west.lat - lat_delta,
44 lng: self.south_west.lng - lng_delta,
45 },
46 north_east: LatLng {
47 lat: self.north_east.lat + lat_delta,
48 lng: self.north_east.lng + lng_delta,
49 },
50 }
51 }
52 
53 pub fn center(&self) -> LatLng {
54 LatLng {
55 lat: (self.south_west.lat + self.north_east.lat) / 2.0,
56 lng: (self.south_west.lng + self.north_east.lng) / 2.0,
57 }
58 }
59}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Returning Option lets a constructor gracefully signal that empty input has no valid result.
  2. 2Copy structs make coordinate math cheap and ergonomic without borrow-checker friction.
  3. 3Converting meters to degrees requires scaling longitude by the cosine of latitude because meridians converge toward the poles.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building geographic bounding boxes in Rust — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code