mapbox-maps-flutter icon indicating copy to clipboard operation
mapbox-maps-flutter copied to clipboard

How can I fit an entire line in my view using bounds?

Open AnEpicName opened this issue 2 years ago • 4 comments

I know this is more of a general question about Mapbox, but I'm not sure how to always display a full route no matter how long it is and how many points it has using this plugin.

I've used something like map.fitBounds(...) in JS in the past, but I'm not sure about how to get those bounds here.

Or maybe if someone knows a better way to do it I would be very thankful!

AnEpicName avatar Feb 22 '23 20:02 AnEpicName

You could use something like this

CoordinateBounds getBoundsFromCoordinates(List<Position> coords) {
  num x0, y0, x1, y1;

  x0 = x1 = coords[0].lat;
  y0 = y1 = coords[0].lng;

  for (Position latLng in coords) {
    if (latLng.lat > x1)
      x1 = latLng.lat;
    if (latLng.lat < x0)
      x0 = latLng.lat;
    if (latLng.lng > y1)
      y1 = latLng.lng;
    if (latLng.lng < y0)
      y0 = latLng.lng;
  }

  // check to keep bounds in range
  x0 = x0 > 90 ? 90 : x0;
  x1 = x1 > 90 ? 90 : x1;
  y0 = y0 > 180 ? 180 : y0;
  y1 = y1 > 180 ? 180 : y1;

  return CoordinateBounds(
    northeast: Point(
      coordinates: Position(y1, x1),
    ).toJson(),
    southwest: Point(
      coordinates: Position(y0, x0)
    ).toJson(),
    infiniteBounds: false,
  );
}

and then use this to get the camera for coordinate bounds

CoordinateBounds bounds = getBoundsFromCoordinates(coords);

final CameraOptions cameraOpt = await _mapboxMap.cameraForCoordinateBounds(
  bounds,
  MbxEdgeInsets(
    // use whatever padding you need
    left: 50,
    top: 50,
    bottom: 50,
    right: 50,
  ),
  null,
  null,
);

// set camera to bounds.
_mapboxMap.setCamera(cameraOpt);

ivan-ljubicic avatar Feb 23 '23 18:02 ivan-ljubicic

Or a simpler solution of using _mapboxMap.cameraForCoordinates to get the camera options for the list of coordinates and then using that CameraOptions with _mapboxMap.setCamera

ivan-ljubicic avatar Mar 05 '23 17:03 ivan-ljubicic

this works in the onMapCreated callback or after the MapWidget has created a MapboxMap object.

But is there a way to get a cameraOptions object before the MapWidget is created that has a center and a zoom parameter for the box and create the MapWidget directly with it ?

ghost avatar Mar 05 '23 21:03 ghost

this works in the onMapCreated callback or after the MapWidget has created a MapboxMap object.

But is there a way to get a cameraOptions object before the MapWidget is created that has a center and a zoom parameter for the box and create the MapWidget directly with it ?

@jeanantoine were you able to achieve this ?

sikandernoori avatar Jan 19 '24 15:01 sikandernoori