mapbox / mapbox-maps-flutter

Interactive, thoroughly customizable maps for Flutter powered by Mapbox Maps SDK
https://www.mapbox.com/mobile-maps-sdk
Other
279 stars 109 forks source link

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

Open AnEpicName opened 1 year ago

AnEpicName commented 1 year ago

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!

ivan-ljubicic commented 1 year ago

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 commented 1 year ago

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

ghost commented 1 year ago

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 ?

sikandernoori commented 8 months ago

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 ?