Annie Hill
Annie Hill

Reputation: 379

Keep all markers in view with Flutter Google Maps plugin

I'm creating an app with flutter using this package: https://github.com/flutter/plugins/tree/master/packages/google_maps_flutter

I get a list of locations from my server, where I must place markers on the map. The problem I am facing is that all markers placed on the map must be visible on the map. The list of locations is random, so I cannot assume if they will all be in one city, or will they be spread across the planet. How could I achieve keeping all markers in view?

Upvotes: 3

Views: 2880

Answers (1)

Shadab Hashmi
Shadab Hashmi

Reputation: 377

Try below code. It is working with hundreds of markers.

  // Set<Marker> _markers = Set();
  @override
  Widget build(BuildContext context) {
    return GoogleMap(
      mapType: MapType.hybrid,
      myLocationEnabled: true,
      initialCameraPosition: CameraPosition(
          target: LatLng(_bloc.location.latitude, _bloc.location.longitude),
          zoom: 3),
      markers: _markers,
      onMapCreated: (GoogleMapController controller) {
        _controller.complete(controller);
        Future.delayed(
            Duration(milliseconds: 200),
            () => controller.animateCamera(CameraUpdate.newLatLngBounds(
                MapUtils.boundsFromLatLngList(
                    _markers.map((loc) => loc.position).toList()),
                1)));
      },
    );
  }

map_utils.dart

import 'package:google_maps_flutter/google_maps_flutter.dart';

class MapUtils {
  static LatLngBounds boundsFromLatLngList(List<LatLng> list) {
    double x0, x1, y0, y1;
    for (LatLng latLng in list) {
      if (x0 == null) {
        x0 = x1 = latLng.latitude;
        y0 = y1 = latLng.longitude;
      } else {
        if (latLng.latitude > x1) x1 = latLng.latitude;
        if (latLng.latitude < x0) x0 = latLng.latitude;
        if (latLng.longitude > y1) y1 = latLng.longitude;
        if (latLng.longitude < y0) y0 = latLng.longitude;
      }
    }
    return LatLngBounds(northeast: LatLng(x1, y1), southwest: LatLng(x0, y0));
  }
} 

Upvotes: 7

Related Questions