mln-rs-map 0.0.7

Part of mln-rs, a Rust port of the MapLibre Native map rendering core. Depend on mln-rs instead.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
// Ports include/mln/map/map.hpp and src/mln/map/map.cpp (the parts M1 runs).

use crate::map_impl::{MapImpl, StillImageCallback, StillImageRequest, StyleMut};
use crate::map_observer::MapObserver;
use crate::map_options::MapOptions;
use mln_map_types::{
    AnimationOptions, BoundOptions, CameraOptions, ConstrainMode, MapDebugOptions, MapMode, NorthOrientation,
    ProjectionMode, TileLodMode, TransformState, ViewportMode,
};
use mln_renderer::{ExceptionPtr, RendererFrontend};
use mln_storage::{ClientOptions, FileSourceManager, FileSourceType, ResourceOptions};
use mln_style::Style;
use mln_util::exception::MisuseException;
use mln_util::geo::{EdgeInsets, ScreenCoordinate};
use mln_util::size::Size;
use mln_storage::FileSource;
use mln_util::geo::{LatLng, LatLngBounds, WrapMode};
use std::cell::Ref;
use std::rc::Rc;
use std::sync::Arc;

pub struct Map {
    impl_: Rc<MapImpl>,
}

impl Map {
    /// `Map(RendererFrontend&, MapObserver&, const MapOptions&)` with the
    /// default `ResourceOptions()` and `ClientOptions()`.
    ///
    /// C++ keeps a reference to the frontend; frontends are handles here
    /// (`Clone` shares the same renderer), so the map keeps a clone.
    pub fn new<F>(frontend: &F, observer: Rc<dyn MapObserver>, map_options: MapOptions) -> Map
    where
        F: RendererFrontend + Clone + 'static,
    {
        Self::with_resource_options(
            frontend,
            observer,
            map_options,
            &ResourceOptions::default(),
            &ClientOptions::default(),
        )
    }

    /// `Map(RendererFrontend&, MapObserver&, const MapOptions&, const
    /// ResourceOptions&, const ClientOptions&)`: the file source is the
    /// FileSourceManager's `ResourceLoader` for these options.
    // TODO(port): ActionJournalOptions.
    pub fn with_resource_options<F>(
        frontend: &F,
        observer: Rc<dyn MapObserver>,
        map_options: MapOptions,
        resource_options: &ResourceOptions,
        client_options: &ClientOptions,
    ) -> Map
    where
        F: RendererFrontend + Clone + 'static,
    {
        let file_source =
            FileSourceManager::get().get_file_source(FileSourceType::ResourceLoader, resource_options, client_options);
        Map {
            impl_: MapImpl::new(Box::new(frontend.clone()), observer, file_source, &map_options),
        }
    }

    // gtests-core: the C++ tests' `MapAdapter` (test/include/mln/test/
    // map_adapter.hpp), i.e. `Map(std::make_unique<Map::Impl>(frontend,
    // observer, fileSource, options))`: a map over a given file source.
    /// `Map(std::unique_ptr<Impl>)` with `Impl(frontend, observer, fileSource, mapOptions)`.
    pub fn with_file_source<F>(
        frontend: &F,
        observer: Rc<dyn MapObserver>,
        file_source: Arc<dyn FileSource>,
        map_options: MapOptions,
    ) -> Map
    where
        F: RendererFrontend + Clone + 'static,
    {
        Map {
            impl_: MapImpl::new(Box::new(frontend.clone()), observer, Some(file_source), &map_options),
        }
    }

    /// `getClientOptions()`.
    pub fn get_client_options(&self) -> ClientOptions {
        match &self.impl_.file_source {
            Some(file_source) => file_source.get_client_options(),
            None => ClientOptions::default(),
        }
    }


    /// Register a callback that will get called (on the render thread) when
    /// all resources have been loaded and a complete render occurs.
    pub fn render_still(&mut self, callback: StillImageCallback) {
        let impl_ = &self.impl_;
        if impl_.mode != MapMode::Static && impl_.mode != MapMode::Tile {
            callback(Some(misuse("Map is not in static or tile image render modes")));
            return;
        }

        if impl_.still_image_request.borrow().is_some() {
            callback(Some(misuse("Map is currently rendering an image")));
            return;
        }

        let last_error = impl_.style.borrow().impl_.get_last_error();
        if let Some(error) = last_error {
            callback(Some(error));
            return;
        }

        *impl_.still_image_request.borrow_mut() = Some(StillImageRequest { callback });

        impl_.on_update();
    }

    /// `renderStill(const CameraOptions&, MapDebugOptions, StillImageCallback)`.
    pub fn render_still_with_camera(
        &mut self,
        camera: &CameraOptions,
        debug_options: MapDebugOptions,
        callback: StillImageCallback,
    ) {
        self.impl_.camera_mutated.set(true);
        self.impl_.debug_options.set(debug_options);
        self.impl_.transform.borrow_mut().jump_to(camera);
        self.render_still(callback);
    }

    /// Triggers a repaint.
    pub fn trigger_repaint(&mut self) {
        self.impl_.on_update();
    }

    // MARK: - Style

    /// `const style::Style& getStyle() const`.
    pub fn get_style(&self) -> Ref<'_, Style> {
        self.impl_.style.borrow()
    }

    /// `style::Style& getStyle()`: a guard that derefs to `&mut Style`; the
    /// style's observer calls made through it reach the map when it drops.
    pub fn get_style_mut(&mut self) -> StyleMut<'_> {
        StyleMut::new(&self.impl_)
    }

    // TODO(port): setStyle(std::unique_ptr<style::Style>).

    // MARK: - Transitions

    pub fn cancel_transitions(&mut self) {
        self.impl_.transform.borrow_mut().cancel_transitions();
        self.impl_.on_update();
    }

    pub fn set_gesture_in_progress(&mut self, in_progress: bool) {
        self.impl_.transform.borrow_mut().set_gesture_in_progress(in_progress);
        self.impl_.on_update();
    }

    pub fn is_gesture_in_progress(&self) -> bool {
        self.impl_.transform.borrow().is_gesture_in_progress()
    }

    pub fn is_rotating(&self) -> bool {
        self.impl_.transform.borrow().is_rotating()
    }

    pub fn is_scaling(&self) -> bool {
        self.impl_.transform.borrow().is_scaling()
    }

    pub fn is_panning(&self) -> bool {
        self.impl_.transform.borrow().is_panning()
    }

    // MARK: - Camera

    pub fn get_camera_options(&self, padding: Option<EdgeInsets>) -> CameraOptions {
        self.impl_.transform.borrow().get_camera_options(padding)
    }

    pub fn jump_to(&mut self, camera: &CameraOptions) {
        self.impl_.jump_to(camera);
    }

    // query: the render-test runner's tile mode uses it.
    /// `latLngBoundsForCamera(camera)`.
    pub fn lat_lng_bounds_for_camera(&self, camera: &CameraOptions) -> mln_util::geo::LatLngBounds {
        let mut shallow = crate::transform::Transform::from_state(self.impl_.transform.borrow().get_state().clone());
        let size = shallow.get_state().get_size();

        shallow.jump_to(camera);
        mln_util::geo::LatLngBounds::hull(
            shallow.screen_coordinate_to_lat_lng(&ScreenCoordinate::new(0.0, 0.0), mln_util::geo::WrapMode::Wrapped),
            shallow.screen_coordinate_to_lat_lng(
                &ScreenCoordinate::new(f64::from(size.width), f64::from(size.height)),
                mln_util::geo::WrapMode::Wrapped,
            ),
        )
    }

    pub fn ease_to(&mut self, camera: &CameraOptions, animation: &AnimationOptions) {
        self.impl_.camera_mutated.set(true);
        self.impl_.transform.borrow_mut().ease_to(camera, animation);
        self.impl_.on_update();
    }

    pub fn fly_to(&mut self, camera: &CameraOptions, animation: &AnimationOptions) {
        self.impl_.camera_mutated.set(true);
        self.impl_.transform.borrow_mut().fly_to(camera, animation, false);
        self.impl_.on_update();
    }

    pub fn move_by(&mut self, point: &ScreenCoordinate, animation: &AnimationOptions) {
        self.impl_.camera_mutated.set(true);
        self.impl_.transform.borrow_mut().move_by(point, animation);
        self.impl_.on_update();
    }

    pub fn pitch_by(&mut self, pitch: f64, animation: &AnimationOptions) {
        let current = mln_math::rad2deg(self.impl_.transform.borrow().get_pitch());
        self.ease_to(&CameraOptions::default().with_pitch(Some(current - pitch)), animation);
    }

    pub fn scale_by(&mut self, scale: f64, anchor: Option<ScreenCoordinate>, animation: &AnimationOptions) {
        let zoom = {
            let transform = self.impl_.transform.borrow();
            transform.get_zoom() + transform.get_state().scale_zoom(scale)
        };
        self.ease_to(&CameraOptions::default().with_zoom(Some(zoom)).with_anchor(anchor), animation);
    }

    pub fn rotate_by(&mut self, first: &ScreenCoordinate, second: &ScreenCoordinate, animation: &AnimationOptions) {
        self.impl_.camera_mutated.set(true);
        self.impl_.transform.borrow_mut().rotate_by(first, second, animation);
        self.impl_.on_update();
    }

    // gtests-core: cameraForLatLngBounds, cameraForLatLngs,
    // latLngBoundsForCameraUnwrapped (test/map/map.test.cpp).
    /// `cameraForLatLngBounds(bounds, padding, bearing, pitch)`.
    pub fn camera_for_lat_lng_bounds(
        &self,
        bounds: &LatLngBounds,
        padding: &EdgeInsets,
        bearing: Option<f64>,
        pitch: Option<f64>,
    ) -> CameraOptions {
        self.camera_for_lat_lngs(
            &[bounds.northwest(), bounds.southwest(), bounds.southeast(), bounds.northeast()],
            padding,
            bearing,
            pitch,
        )
    }

    /// `cameraForLatLngs(latLngs, padding, bearing, pitch)`.
    pub fn camera_for_lat_lngs(
        &self,
        lat_lngs: &[LatLng],
        padding: &EdgeInsets,
        bearing: Option<f64>,
        pitch: Option<f64>,
    ) -> CameraOptions {
        if bearing.is_none() && pitch.is_none() {
            return camera_for_lat_lngs(lat_lngs, &self.impl_.transform.borrow(), padding);
        }

        let mut transform = crate::transform::Transform::from_state(self.impl_.transform.borrow().get_state().clone());

        transform.jump_to(&CameraOptions::default().with_bearing(bearing).with_pitch(pitch));

        camera_for_lat_lngs(lat_lngs, &transform, padding)
            .with_bearing(Some(mln_math::rad2deg(-transform.get_bearing())))
            .with_pitch(Some(mln_math::rad2deg(transform.get_pitch())))
    }

    // TODO(port): cameraForGeometry.

    /// `latLngBoundsForCameraUnwrapped(camera)`.
    pub fn lat_lng_bounds_for_camera_unwrapped(&self, camera: &CameraOptions) -> LatLngBounds {
        let mut shallow = crate::transform::Transform::from_state(self.impl_.transform.borrow().get_state().clone());
        let size = shallow.get_state().get_size();

        shallow.jump_to(camera);
        let width = f64::from(size.width);
        let height = f64::from(size.height);
        let mut nw = shallow.screen_coordinate_to_lat_lng(&ScreenCoordinate::new(0.0, 0.0), WrapMode::Wrapped);
        let mut se = shallow.screen_coordinate_to_lat_lng(&ScreenCoordinate::new(width, height), WrapMode::Wrapped);
        let mut ne = shallow.screen_coordinate_to_lat_lng(&ScreenCoordinate::new(width, 0.0), WrapMode::Wrapped);
        let mut sw = shallow.screen_coordinate_to_lat_lng(&ScreenCoordinate::new(0.0, height), WrapMode::Wrapped);
        let center =
            shallow.screen_coordinate_to_lat_lng(&ScreenCoordinate::new(width / 2.0, height / 2.0), WrapMode::Wrapped);
        nw.unwrap_for_shortest_path(&center);
        se.unwrap_for_shortest_path(&center);
        ne.unwrap_for_shortest_path(&center);
        sw.unwrap_for_shortest_path(&center);
        let mut bounds = LatLngBounds::hull(nw, se);
        bounds.extend(&ne);
        bounds.extend(&sw);
        bounds.extend(&center);
        bounds
    }

    // MARK: - Bounds

    pub fn set_bounds(&mut self, options: &BoundOptions) -> Result<(), String> {
        let mut change_camera = false;
        let mut camera_options = CameraOptions::default();

        {
            let mut transform = self.impl_.transform.borrow_mut();

            if let Some(bounds) = options.bounds {
                change_camera = true;
                transform.set_lat_lng_bounds(bounds)?;
            }

            if let Some(min_zoom) = options.min_zoom {
                transform.set_min_zoom(min_zoom);
                if transform.get_zoom() < min_zoom {
                    change_camera = true;
                    camera_options = camera_options.with_zoom(options.min_zoom);
                }
            }

            if let Some(max_zoom) = options.max_zoom {
                transform.set_max_zoom(max_zoom);
                if transform.get_zoom() > max_zoom {
                    change_camera = true;
                    camera_options = camera_options.with_zoom(options.max_zoom);
                }
            }

            if let Some(max_pitch) = options.max_pitch {
                transform.set_max_pitch(max_pitch);
                if transform.get_pitch() > transform.get_state().get_max_pitch() {
                    change_camera = true;
                    camera_options = camera_options.with_pitch(options.max_pitch);
                }
            }

            if let Some(min_pitch) = options.min_pitch {
                transform.set_min_pitch(min_pitch);
                if transform.get_pitch() < transform.get_state().get_min_pitch() {
                    change_camera = true;
                    camera_options = camera_options.with_pitch(options.min_pitch);
                }
            }
        }

        if change_camera {
            self.jump_to(&camera_options);
        }
        Ok(())
    }

    /// Returns the current map bound options. All optional fields in
    /// BoundOptions are set.
    pub fn get_bounds(&self) -> BoundOptions {
        let transform = self.impl_.transform.borrow();
        let state = transform.get_state();
        BoundOptions::default()
            .with_lat_lng_bounds(state.get_lat_lng_bounds())
            .with_min_zoom(state.get_min_zoom())
            .with_max_zoom(state.get_max_zoom())
            .with_min_pitch(mln_math::rad2deg(state.get_min_pitch()))
            .with_max_pitch(mln_math::rad2deg(state.get_max_pitch()))
    }

    // MARK: - Map options

    pub fn set_north_orientation(&mut self, orientation: NorthOrientation) {
        self.impl_.transform.borrow_mut().set_north_orientation(orientation);
        self.impl_.on_update();
    }

    pub fn set_constrain_mode(&mut self, mode: ConstrainMode) {
        self.impl_.transform.borrow_mut().set_constrain_mode(mode);
        self.impl_.on_update();
    }

    pub fn set_viewport_mode(&mut self, mode: ViewportMode) {
        self.impl_.transform.borrow_mut().set_viewport_mode(mode);
        self.impl_.on_update();
    }

    /// C++ throws "failed to resize: size is empty"; the port returns it.
    pub fn set_size(&mut self, size: Size) -> Result<(), String> {
        self.impl_.transform.borrow_mut().resize(size)?;
        self.impl_.on_update();
        Ok(())
    }

    pub fn set_frustum_offset(&mut self, frustum_offset: &EdgeInsets) {
        self.impl_.transform.borrow_mut().set_frustum_offset(frustum_offset);
        self.impl_.on_update();
    }

    pub fn get_frustum_offset(&self) -> EdgeInsets {
        self.impl_.transform.borrow().get_frustum_offset()
    }

    pub fn get_map_options(&self) -> MapOptions {
        let transform = self.impl_.transform.borrow();
        let state = transform.get_state();
        MapOptions::new()
            .with_north_orientation(transform.get_north_orientation())
            .with_map_mode(self.impl_.mode)
            .with_constrain_mode(state.get_constrain_mode())
            .with_viewport_mode(state.get_viewport_mode())
            .with_cross_source_collisions(self.impl_.cross_source_collisions)
            .with_size(state.get_size())
            .with_pixel_ratio(self.impl_.pixel_ratio)
    }

    // MARK: - Projection mode

    pub fn set_projection_mode(&mut self, options: &ProjectionMode) {
        self.impl_.transform.borrow_mut().set_projection_mode(options);
        self.impl_.on_update();
    }

    pub fn get_projection_mode(&self) -> ProjectionMode {
        self.impl_.transform.borrow().get_projection_mode()
    }

    // MARK: - Transform

    pub fn get_transform_state(&self) -> TransformState {
        self.impl_.transform.borrow().get_state().clone()
    }

    // MARK: - Tile LOD

    pub fn set_tile_lod_min_radius(&mut self, radius: f64) {
        if self.impl_.tile_lod_min_radius.get() == radius {
            return;
        }
        self.impl_.tile_lod_min_radius.set(radius);
        self.impl_.on_update();
    }

    pub fn get_tile_lod_min_radius(&self) -> f64 {
        self.impl_.tile_lod_min_radius.get()
    }

    pub fn set_tile_lod_scale(&mut self, scale: f64) {
        if self.impl_.tile_lod_scale.get() == scale {
            return;
        }
        self.impl_.tile_lod_scale.set(scale);
        self.impl_.on_update();
    }

    pub fn get_tile_lod_scale(&self) -> f64 {
        self.impl_.tile_lod_scale.get()
    }

    pub fn set_tile_lod_pitch_threshold(&mut self, threshold: f64) {
        if self.impl_.tile_lod_pitch_threshold.get() == threshold {
            return;
        }
        self.impl_.tile_lod_pitch_threshold.set(threshold);
        self.impl_.on_update();
    }

    pub fn get_tile_lod_pitch_threshold(&self) -> f64 {
        self.impl_.tile_lod_pitch_threshold.get()
    }

    pub fn set_tile_lod_zoom_shift(&mut self, shift: f64) {
        if self.impl_.tile_lod_zoom_shift.get() == shift {
            return;
        }
        self.impl_.tile_lod_zoom_shift.set(shift);
        self.impl_.on_update();
    }

    pub fn get_tile_lod_zoom_shift(&self) -> f64 {
        self.impl_.tile_lod_zoom_shift.get()
    }

    pub fn set_tile_lod_mode(&mut self, mode: TileLodMode) {
        if self.impl_.tile_lod_mode.get() == mode {
            return;
        }
        self.impl_.tile_lod_mode.set(mode);
        self.impl_.on_update();
    }

    pub fn get_tile_lod_mode(&self) -> TileLodMode {
        self.impl_.tile_lod_mode.get()
    }

    // gtests-core: projection and prefetch zoom delta (test/map, test/api).
    // MARK: - Projection

    /// `pixelForLatLng(latLng)`.
    pub fn pixel_for_lat_lng(&self, lat_lng: &LatLng) -> ScreenCoordinate {
        // If the center and point longitudes are not in the same side of the
        // antimeridian, we unwrap the point longitude so it would be seen if
        // e.g. the next antimeridian side is visible.
        let transform = self.impl_.transform.borrow();
        let mut unwrapped_lat_lng = lat_lng.wrapped();
        unwrapped_lat_lng.unwrap_for_shortest_path(&transform.get_lat_lng(WrapMode::Wrapped));
        transform.lat_lng_to_screen_coordinate(&unwrapped_lat_lng)
    }

    /// `latLngForPixel(pixel, wrapMode)`.
    pub fn lat_lng_for_pixel(&self, pixel: &ScreenCoordinate, wrap_mode: WrapMode) -> LatLng {
        self.impl_.transform.borrow().screen_coordinate_to_lat_lng(pixel, wrap_mode)
    }

    /// `pixelsForLatLngs(latLngs)`.
    pub fn pixels_for_lat_lngs(&self, lat_lngs: &[LatLng]) -> Vec<ScreenCoordinate> {
        lat_lngs.iter().map(|lat_lng| self.pixel_for_lat_lng(lat_lng)).collect()
    }

    /// `latLngsForPixels(screenCoords, wrapMode)`.
    pub fn lat_lngs_for_pixels(&self, screen_coords: &[ScreenCoordinate], wrap_mode: WrapMode) -> Vec<LatLng> {
        screen_coords
            .iter()
            .map(|point| self.lat_lng_for_pixel(point, wrap_mode))
            .collect()
    }

    /// `setPrefetchZoomDelta(delta)`.
    pub fn set_prefetch_zoom_delta(&mut self, delta: u8) {
        if self.impl_.prefetch_zoom_delta.get() == delta {
            return;
        }
        self.impl_.prefetch_zoom_delta.set(delta);
        self.impl_.on_update();
    }

    /// `getPrefetchZoomDelta()`.
    pub fn get_prefetch_zoom_delta(&self) -> u8 {
        self.impl_.prefetch_zoom_delta.get()
    }

    /// `getFreeCameraOptions()`.
    pub fn get_free_camera_options(&self) -> mln_map_types::FreeCameraOptions {
        self.impl_.transform.borrow().get_free_camera_options()
    }

    // TODO(port): annotations, rendering stats view, setFreeCameraOptions,
    // rendered features.

    // MARK: - Debug

    pub fn set_debug(&mut self, debug_options: MapDebugOptions) {
        self.impl_.debug_options.set(debug_options);
        self.impl_.on_update();
    }

    pub fn get_debug(&self) -> MapDebugOptions {
        self.impl_.debug_options.get()
    }

    pub fn is_fully_loaded(&self) -> bool {
        self.impl_.style.borrow().impl_.is_loaded() && self.impl_.renderer_fully_loaded.get()
    }
}

fn misuse(message: &str) -> ExceptionPtr {
    MisuseException::ptr(message)
}

// gtests-core: the free function `cameraForLatLngs(latLngs, transform,
// padding)` of map.cpp (Map::cameraForLatLngs and MapProjection use it).
pub(crate) fn camera_for_lat_lngs(
    lat_lngs: &[LatLng],
    transform: &crate::transform::Transform,
    padding: &EdgeInsets,
) -> CameraOptions {
    if lat_lngs.is_empty() {
        return CameraOptions::default();
    }
    let size = transform.get_state().get_size();
    // Calculate the bounds of the possibly rotated shape with respect to the viewport.
    let mut ne_pixel = ScreenCoordinate::new(f64::NEG_INFINITY, f64::NEG_INFINITY);
    let mut sw_pixel = ScreenCoordinate::new(f64::INFINITY, f64::INFINITY);
    for lat_lng in lat_lngs {
        let pixel = transform.lat_lng_to_screen_coordinate(lat_lng);
        // std::min / std::max
        sw_pixel.x = if pixel.x < sw_pixel.x { pixel.x } else { sw_pixel.x };
        ne_pixel.x = if ne_pixel.x < pixel.x { pixel.x } else { ne_pixel.x };
        sw_pixel.y = if pixel.y < sw_pixel.y { pixel.y } else { sw_pixel.y };
        ne_pixel.y = if ne_pixel.y < pixel.y { pixel.y } else { ne_pixel.y };
    }
    let width = ne_pixel.x - sw_pixel.x;
    let height = ne_pixel.y - sw_pixel.y;

    // Calculate the zoom level.
    let mut min_scale = f64::INFINITY;
    if width > 0.0 || height > 0.0 {
        let mut scale_x = f64::from(size.width) / width;
        let mut scale_y = f64::from(size.height) / height;
        scale_x -= (padding.left() + padding.right()) / width;
        scale_y -= (padding.top() + padding.bottom()) / height;
        min_scale = mln_math::min_f64(scale_x, scale_y);
    }

    let mut zoom = transform.get_zoom();
    if min_scale > 0.0 {
        zoom = mln_math::clamp_f64(
            zoom + mln_math::log2(min_scale),
            transform.get_state().get_min_zoom(),
            transform.get_state().get_max_zoom(),
        );
    } else {
        mln_util::logging::Log::error(
            mln_util::logging::Event::General,
            "Unable to calculate appropriate zoom level for bounds. Vertical or horizontal padding is greater than \
             map's height or width.",
        );
    }

    // Calculate the center point of a virtual bounds that is extended in all directions by padding.
    let center_pixel = ScreenCoordinate::new((ne_pixel.x + sw_pixel.x) / 2.0, (ne_pixel.y + sw_pixel.y) / 2.0);

    CameraOptions::default()
        .with_center(Some(transform.screen_coordinate_to_lat_lng(&center_pixel, WrapMode::Wrapped)))
        .with_padding(Some(*padding))
        .with_zoom(Some(zoom))
}