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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Returning Option lets a constructor gracefully signal that empty input has no valid result.
- 2Copy structs make coordinate math cheap and ergonomic without borrow-checker friction.
- 3Converting meters to degrees requires scaling longitude by the cosine of latitude because meridians converge toward the poles.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
rust
use std::collections::VecDeque; use std::sync::{Arc, Condvar, Mutex}; use std::time::{Duration, Instant};
Building a counting semaphore in Rust
concurrency
synchronization
condition-variable
Advanced
9 steps
rust
use axum::{ async_trait, extract::{rejection::JsonRejection, FromRequest, Request}, http::StatusCode,
A validated JSON extractor in Axum
extractors
validation
error-handling
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-geographic-bounding-boxes-in-rust-explained-rust-8afb/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.