Flutter Vector Package [ NEW ]

Getting Started

A vector map package for Flutter is a powerful tool that allows you to integrate dynamic and interactive maps into your applications. Unlike traditional raster maps that are made up of static images, vector maps are based on vector data, which means they can be scaled and styled without losing image quality. Vector maps are optimized for performance, enabling smooth and fluid map interactions even on devices with varying levels of processing power.

To install and start using this package in your Flutter project, you need to add "galli_vector_plugin" as a dependency in your project's pubspec.yaml file. You can follow the installation guide provided in the galli_vector_plugin package on pub.dev to access the package page.

dependencies:
	...
	galli_vector_plugin: [latest-version]

Prerequisite

IOS

To use this plugin with iOS, you need to add the source repository and 2 additional pods to your Podfile, as shown in the example.

source 'https://cdn.cocoapods.org/'
source 'https://github.com/m0nac0/flutter-maplibre-podspecs.git'
					
pod 'MapLibre'
pod 'MapLibreAnnotationExtension'

Android

To use this plugin with android, you need to add the following lines of code in android\app\build.gradle, as shown in the example

dependencies {
	constraints {
		implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.8.0") {
			because("kotlin-stdlib-jdk7 is now a part of kotlin-stdlib")
		}
		implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.8.0") {
			because("kotlin-stdlib-jdk8 is now a part of kotlin-stdlib")
		}
	}
}

Note: Minimum sdk version 21

Location features

IOS

To enable location features in an iOS application:

If you access your users' location, you should also add the following key to ios/Runner/Info.plist to explain why you need access to their location data as in example:

xml ...
	<key>NSLocationWhenInUseUsageDescription</key>
	<string>[Your explanation here]</string>

ANDROID

Add the ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission in the application manifest android/app/src/main/AndroidManifest.xml to enable location features as shown in example:

<manifest ...
	<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
	<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

Widgets

1. GalliMap Widget

A vector map widget for Flutter. To use this widget import and add the GalliMap widget to the project.

Example :

GalliMapController? controller;
GalliMap(
	size: (
		height: MediaQuery.of(context).size.height * 0.8,
		width: MediaQuery.of(context).size.width * 0.8,
	 	),
	compassPosition: (
		position: CompassViewPosition.TopRight,
		offset: null
	  ),
	showCompass: true,
		onMapCreated: (newC) {
		controller = newC;
		},
	)
Property Type Required Default Description
size Record({double height, double width}) True null Sets the size of the map widget.
onMapCreated Function(GalliMapController controller) False null Callback when the map is created.
showCurrentLocation Bool False True Shows a default user location marker, asks for user location if true.
showCompass Bool False True To show or not to show the compass widget. To show a custom compass widget, disable the default compass widget and pass a custom widget in children. You can use the compass package to get user bearing and use animateMap to rotate map to north.
showCurrentLocationButton Bool False True It will display a button. When tapped, it will show the current location.
showSearchWidget Bool False True Used to search the location. When the user taps on it, they can search for the location.
showThree60Widget Bool False True Determines whether to display a Three60 widget. A Three60 widget provides a 360-degree view or interactive experience. When set to true (default), the widget will be shown. If set to false, the widget will not be displayed, potentially saving screen space or enhancing the user experience differently.
compassPosition Record ({CompassViewPosition? position, Point<num>? offset}) False {position: CompassViewPosition.BottomRight, offset: const Point(30, 48)} Default value for compass position. It includes the position (BottomRight, BottomLeft, TopRight, TopLeft) and offset to pad the compass widget from the viewport.
onMapCreated Function(GalliMapController controller)? False null Callback function after the map has been created and is ready for interaction. It can be used for additional configurations or actions related to the map.
onMapClick Function(LatLng latlng)? False null Callback function for handling user clicks or interactions with the map. Takes a LatLng parameter representing the geographic coordinates of the click.
initialCameraPostion CameraPosition False CameraPosition(target: LatLng(27.677120, 85.322313,), zoom: 18, bearing: 0.0, tilt: 0) Callback function for handling user clicks or interactions with the map. Takes a LatLng parameter representing the geographic coordinates of the click.
onUserLocationChanged Function(UserLocation location)? False null Callback function for handling changes in the user's location on a map. Expects a UserLocation parameter containing latitude, longitude, altitude, and other location attributes.
authToken final String authToken; True null The authToken needed to run the app.
minMaxZoomPreference MinMaxZoomPreference False const MinMaxZoomPreference(4.5, 22) Specifies the minimum and maximum zoom levels allowed on a map. Default allows zoom levels between 4.5 (fairly zoom-out) and 22 (fairly zoomed-in).
zoomGestureEnabled bool False True Controls whether zooming in and out of the map using gestures is enabled or disabled.
doubleClickZoomEnabled bool False True Controls whether zooming using a double-click or double-tap gesture is enabled or disabled.
dragEnabled bool False True Controls whether users can drag or pan the map by clicking and dragging.
rotateGestureEnabled bool False True Controls whether users can rotate the map using gestures.
tiltGestureEnabled bool False True Controls whether users can tilt or change the perspective of the map using gestures.
scrollGestureEnabled bool False True Controls whether users can scroll or pan the map by swiping or scrolling on the device's touch screen.
onMapLongPress Function(LatLng latLng)? False null Callback function for handling long-press or long-tap events on a map. Takes a LatLng parameter representing the location where the long-press occurred.
children List<Widget> False const [] A list of child widgets to be added or displayed within a parent widget or component.

2. Galli Search Widget

A search widget (search bar) that takes the search text and returns search results. To use this widget import and add the GalliSearchWidget to the project.

Example :

GalliSearchWidget(
 width: 50,
 hint:hint
 authToken: "Token",
 mapController: galliMapController,
)
Property Type Required Default Description
authToken String True null Takes the access token (auth token) key.
mapController GalliMapController True null Takes the galli map controller.
hint String False null Displays the hint text.
onAutoCompleteResultTap Function(Map data) False null Function that runs when an auto-complete result is tapped.
width double? False null Width of the search bar.
height double False 48 Height of the search bar, defined as 48.

3. Current Location Widget

A current location button which returns the real time location of the user. To use this widget import and add the CurrentLocationWidget to the project.

Example :

CurrentLocationWidget(
	controller: galliMapController
)
Property Type Required Default Description
controller GalliMapController True null Galli Map Controller to get the current location of user.

4. Three60Button Widget

A 360 button which returns the locations of 360 images. To use this widget import and add the Three60Button widget to the project.

Example :

Three60ButtonWidget(controller: galliMapController)
Property Type Required Default Description
controller GalliMapController True null Galli Map Controller to get the 360 locations.

5. GalliViewer Widget

A 360 Viewer to display 360 images. To use this widget import and add the GalliViewer widget to the project.

Example :

GalliViewer(
  builder: (BuildContext context, Function() methodFromChild) {
  	clearMarkers = methodFromChild;
  },
  errorBuilder: (Object? error) {},
  loadingBuilder: (double? progress) {},
  onLongPress: (latitude, longitude, tilt) {},
  onMarkerTap: (latitude, longitude) {},
  addMarkerOnTap: true,
  removeMarkerOnTap: true,
  showClearMarkersButton: true,
  image: value,
  onTap: (latitude, longitude, tilt) {},
  markers: markers,
  maxMarkers: 2,
);
Property Type Required Default
Image String True null
errorBuilder Function(Object? error) False null
loadingBuilder Function(double? progress) False null
onTap Function(double x, double y, double z) False null
onLongPress Function(double x, double y, double z) False null
addMarkerOnTap bool False true
markers List<Marker> False const[]
maxMarkers int False 99
showClearMarkersButton bool False true
removeMarkerOnTap bool False true
onMarkerOnTap Function(double latitude, double longitude) False null

GalliMethods


1. get360Image

It is used to fetch a 360-degree image from a location-based service, and it includes error handling to handle any potential issues that may arise during the image retrieval process.

Example :

try {
// Call the get360Image method
	var image = await methods.get360Image(
	LatLng(27.67716169091915, 85.32351400940793),
	threshold: 20,
	);

	// Now you can use the 'image' variable to access the 360-degree image data or URL
	print('360-degree image URL: $image');
	} catch (e) {
	// Handle any errors that may occur
	print('Error fetching 360-degree image: $e');
  }

2. autoComplete

It will autocomplete the search result on the basis of input string.

Example :

methods.autoComplete("san");

3. getRoute

When you call methods.getRoute, it sends a request to a routing or mapping service to calculate and provide a route or directions from the source location to the destination location. The service will respond with information about the route, which may include step-by-step directions, distance, estimated travel time, and other relevant details.

Example :

methods.getRoute(
	source: LatLng(27.67716169091915, 85.32351400940793),
	destination: LatLng(27.67649922688999, 85.32053625519644));

4. reverse

When we call a reverse method with a specific latitude and longitude coordinate represented as a LatLng object. This code is likely related to performing reverse geocoding, which is the process of converting geographic coordinates (latitude and longitude) into human-readable location information, such as an address or place name.

Example :

methods.reverse(LatLng(27.67716169091915, 85.32351400940793));

5. search

It appears to be calling a search method with two arguments: a search query and a LatLng object representing geographic coordinates. This code is likely related to searching for a specific location or place based on the provided query and coordinates.

Example :

methods.search(
	'houseNumber', LatLng(27.67716169091915, 85.32351400940793));

Map Controllers


1. animateCamera

Starts an animated change of the map camera position. Duration is the amount of time, that the transition animation should take. The returned [Future] completes after the change has been started on the platform side. It returns true if the camera was successfully moved and false if the movement was canceled.
Note: this currently always returns immediately with a value of null on iOS

Example :

LatLng? myLocation =await controller!.requestMyLocationLatLng();
controller!.animateCamera(CameraUpdate.newLatLng(myLocation!),duration: const Duration(milliseconds: 500));
controller!.animateCamera(CameraUpdate.newLatLngZoom(myLocation, 18));
controller!.animateCamera(CameraUpdate.bearingTo(0.0)); //animates to north
controller!.animateCamera(CameraUpdate.tiltTo(60)); // 3d view
controller!.animateCamera(CameraUpdate.newCameraPosition(CameraPosition(target: myLocation, bearing: 40, tilt: 30, zoom: 12)));
controller!.animateCamera(CameraUpdate.zoomTo(50.0));
controller!.animateCamera(CameraUpdate.zoomBy(-0.5));//Zoom out in .5 
controller!.animateCamera(CameraUpdate.zoomIn());/// Returns a camera update that zooms the camera in, bringing the camera
  /// closer to the surface of the Earth.
 
  /// Equivalent to the result of calling `zoomBy(1.0)`

2. moveCamera

Instantaneously re-position the camera. The returned [Future] completes after the change has been made on the platform side. It returns true if the camera was successfully moved and false if the movement was canceled.
Note: this currently always returns immediately with a value of null on iOS. moveCamera() quickly moves the camera, which can be visually jarring for a user. Strongly consider using the animateCamera() methods instead because it's less abrupt

Example:


controller!.moveCamera(CameraUpdate.newLatLngZoom(myLocation, 18));
controller!.moveCamera(CameraUpdate.newCameraPosition(CameraPosition(target: myLocation, bearing: 40, tilt: 30, zoom: 12)));
controller!.moveCamera(CameraUpdate.bearingTo(45.0));///// Returns a camera update that sets the camera bearing.
controller!.moveCamera(CameraUpdate.tiltTo(35.0));///// Returns a camera update that sets the camera bearing.
controller!.moveCamera(CameraUpdate.scrollBy(50, 75));/// Returns a camera update that moves the camera target the specified screen
  /// distance.
  ///
  /// For a camera with bearing 0.0 (pointing north), scrolling by 50,75 moves
  /// the camera's target to a geographical location that is 50 to the east and
  /// 75 to the south of the current location, measured in screen coordinates.

controller!.moveCamera( CameraUpdate.newLatLngBounds(LatLngBounds(southwest: const LatLng(28, 50), northeast: const LatLng(84.982446, 53.823821),),left: 10,top: 5, bottom: 25,),);/// Returns a camera update that transforms the camera so that the specified
  /// geographical bounding box is centered in the map view at the greatest
  /// possible zoom level. A non-zero [left], [top], [right] and [bottom] padding
  /// insets the bounding box from the map view's edges.
  /// The camera's new tilt and bearing will both be 0.0.
	

3. addGeoJsonSource

Adds a new geojson source. The json in [geojson] has to comply with the schema for FeatureCollection as specified in https://datatracker.ietf.org/doc/html/rfc7946#section-3.3 [promoteId] can be used on web to promote an id from properties to be the id of the feature. This is useful because by default mapbox-gl-js does not support string ids. The returned [Future] completes after the change has been made on the platform side.

Example:


const _points = {
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "id": 2,
      "properties": {
        "type": "restaurant",
      },
      "geometry": {
        "type": "Point",
        "coordinates": [151.184913929732943, -33.874874486427181]
      }
    },
    {
      "type": "Feature",
      "id": 3,
      "properties": {
        "type": "airport",
      },
      "geometry": {
        "type": "Point",
        "coordinates": [151.215730044667879, -33.874616048776858]
      }
    },
    {
      "type": "Feature",
      "id": 4,
      "properties": {
        "type": "bakery",
      },
      "geometry": {
        "type": "Point",
        "coordinates": [151.228803547973598, -33.892188026142584]
      }
    },
    {
      "type": "Feature",
      "id": 5,
      "properties": {
        "type": "college",
      },
      "geometry": {
        "type": "Point",
        "coordinates": [151.186470299174118, -33.902781145804774]
      }
    }
  ]
};
await controller.addGeoJsonSource("points", _points);
	

4. setGeoJsonSource

Sets new geojson data to an existing source. This only works as expected if the source has been created with [addGeoJsonSource] before. This is very useful if you want to update an existing source with modified data. The json in [geojson] has to comply with the schema for FeatureCollection as specified in https://datatracker.ietf.org/doc/html/rfc7946#section-3.3. The returned [Future] completes after the change has been made on the platform side.

Example:


const _points = {
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "id": 2,
      "properties": {
        "type": "restaurant",
      },
      "geometry": {
        "type": "Point",
        "coordinates": [151.184913929732943, -33.874874486427181]
      }
    },
    {
      "type": "Feature",
      "id": 3,
      "properties": {
        "type": "airport",
      },
      "geometry": {
        "type": "Point",
        "coordinates": [151.215730044667879, -33.874616048776858]
      }
    },
    {
      "type": "Feature",
      "id": 4,
      "properties": {
        "type": "bakery",
      },
      "geometry": {
        "type": "Point",
        "coordinates": [151.228803547973598, -33.892188026142584]
      }
    },
    {
      "type": "Feature",
      "id": 5,
      "properties": {
        "type": "college",
      },
      "geometry": {
        "type": "Point",
        "coordinates": [151.186470299174118, -33.902781145804774]
      }
    }
  ]
};
Map<String, dynamic> buildFeatureCollection(
    List<Map<String, dynamic>> features) {
  return {"type": "FeatureCollection", "features": features};
}
await controller.setGeoJsonSource(
          "points",
          buildFeatureCollection(
              [for (final l in _idToAnnotation.values) l.toGeoJson()]));
	

5. Draw a Polygon

a. addFill

The shape of the polygon depends on the geometry value where we pass the LatLng value. The fillColor, fillOpacity, fillOutlined defines the color, opacity, and the outlined border of the polygon. The value of draggable true means we can drag the polygon shape anywhere as our needs. fill is the type of Polygon, and it will hold a reference to the polygon you added to the map.


fill = await controller!.addFill(
    FillOptions(
        geometry: [
            // Array of LatLng values
        ],
        fillColor: "#FF0000",
        fillOutlineColor: "#FF0000",
        fillOpacity: 0.25,
        draggable: true,
    ),
);

b. addFills

Multiple fills will appear as per their defined geometry where we can change the color, opacity, outline color, pattern as described below. We can add as many addfills.


final List<FillOptions> FillOptionList = [
    FillOptions(
        geometry: _defaultGeometry,
        fillColor: "#FF0000",
        fillOutlineColor: "#FF0000",
        fillOpacity: 0.75,
        draggable: true,
        fillPattern: 'assets/images/bank.png',
    ),
];
await controller!.addFills(FillOptionList);

c. clearFills

It clears all the fills at once which have been created.


await controller!.clearFills();

d. updateFills

We can update the fills as per their requirement with their geometry, color, opacity, and outline color.


final FillOptions changes = FillOptions(
    geometry: _defaultGeometry,
    fillColor: "#FF0000",
    fillOutlineColor: "#FF0000",
    fillOpacity: 0.75,
    draggable: true,
    fillPattern: 'assets/images/bank.png',
);

await controller!.updateFill(fill!, changes);

e. removeFill

It will remove the polygon if there is any polygon.


controller!.removeFill(fill!);

f. removeFills

It will remove the fills which have been created. The _fills mentioned below were stored in the list.


await controller!.removeFills(_fills);

6. Circles

a. addCircle

Draw a Circle Shape. The location of the circle lies according to the geometry which is LatLng. The radius of the circle will be formed at the given location as per the given radius. The circleColor, circleOpacity, circleStrokeColor, circleStrokeWidth, circleStrokeOpacity define the color, opacity, stroke color, width of stroke, and stroke opacity. Draggable true means we can drag the circle on the map.


// _selectedCircle is of type Circle, and it will hold a reference to the circle you added to the map.
_selectedCircle = await controller!.addCircle(   
    circleRadius: 60,
    geometry: LatLng(27.67649922688999, 85.32053625519644),
    circleColor: "#FF0000",
    circleOpacity: .25,
    circleStrokeColor: "#0000FF",
    circleStrokeWidth: 2.0,
    circleStrokeOpacity: .5,
    circleBlur: 1,
    draggable: true),

b. updateCircle

It will update the circles as per the mentioned changes. The update circle can be mentioned with their radius, opacity, stroke, stroke width, as mentioned below.


controller!.animateCamera(CameraUpdate.newLatLng(
    LatLng(27.67784997449824, 85.31975107971293)));

final CircleOptions changes = CircleOptions(
    geometry: LatLng(27.67784997449824, 85.31975107971293),
    circleRadius: 30,
    circleColor: "#0000FF",
    circleStrokeOpacity: .2,
    circleStrokeColor: "#FF0000",
    circleStrokeWidth: 3,
    circleOpacity: .8);

await controller!.updateCircle(_selectedCircle!, changes);

c. addCircles

Multiple circles can be added with their defined properties like radius, color, stroke color, stroke width. We can add as many circles as we want from the given example of code.


final List<CircleOptions> circleOptionsList = [
    CircleOptions(
        geometry: LatLng(27.67784997449824, 85.31975107971293),
        circleRadius: 30,
        circleColor: "#0000FF",
        circleStrokeOpacity: .2,
        circleStrokeColor: "#FF0000",
        circleStrokeWidth: 3,
        circleOpacity: .8,
        draggable: true),
];

await controller!.addCircles(circleOptionsList);

d. removeCircle

It will remove the circle if there is any circle.


controller!.removeCircle(_selectedCircle!);

e. removeCircles

It will remove the circles which have been created. The _circles mentioned below were stored in the list.


await controller!.removeCircles(_circles);

f. getCircleLatLng

We can get the circle Latitude Longitude which has been created of the _selectedCircle.


await controller!.getCircleLatLng(_selectedCircle!);

g. clearCircles

It will clear all the circles which have been created at once.


await controller!.clearCircles();

7. Polyline

a. addLine

The line appears on the map depending on the geometry provided by the user, which is LatLng. The lineColor, lineWidth, lineOpacity mean color, width, opacity. The lineJoin means the shape at the join on different geometry. The lineGapwidth means the gap in the middle of the line. Draggable true means we can drag the line.


// _selectedLine is of type Line, and it will hold a reference to the Line you added to the map.
_selectedLine = await controller!.addLine(LineOptions(
    geometry: [
        LatLng(27.6746453246322, 85.33441614189833),
        LatLng(27.675822921057367, 85.32545000104156),
        LatLng(27.6829891627444, 85.32609586712023),
        LatLng(27.68292187627674, 85.3320986224396),
    ],
    lineColor: "#ff0000",
    lineWidth: 15.0,
    lineOpacity: 0.5,
    draggable: true,
    lineJoin: 'round',
    lineGapWidth: 2,
    lineBlur: 3,
    lineOffset: 2,
));

b. updateLine

It will update the lines from the start and end point. The line will be updated as per the mentioned condition.


final currentStart = _selectedLine!.options.geometry![0];
final currentEnd = _selectedLine!.options.geometry![1];

// Calculate the new coordinates for the start and end points
const offset = 0.001;
const end = LatLng(currentEnd.latitude + offset, currentEnd.longitude + offset);
const start = LatLng(currentStart.latitude - offset, currentStart.longitude - offset);

// Update the line's geometry with the new start and end points
await controller!.updateLine(_selectedLine!, LineOptions(geometry: [start, end]));

c. addLines

Multiple lines can be added. The added line can have their properties like color, geometry, opacity, blur, offset, as mentioned below.


final List<SLineOptions> LineOptionsList = [
    LineOptions(
        geometry: [
            LatLng(27.6746453246322, 85.33441614189833),
            LatLng(27.675822921057367, 85.32545000104156),
            LatLng(27.6829891627444, 85.32609586712023),
            LatLng(27.68292187627674, 85.3320986224396),
        ],
        lineColor: "#ff0000",
        lineWidth: 15.0,
        lineOpacity: 0.5,
        draggable: true,
        lineJoin: 'round',
        lineGapWidth: 2,
        lineBlur: 3,
        lineOffset: 2,
    )
];

await controller!.addLines(LineOptionsList);

d. removeLine

It will remove the line if there is any line.


controller!.removeLine(_selectedLine!);

e. removeLines

It will remove the lines which have been created. The _lines list stores the created line.


await controller!.removeLines(_lines);

f. clearLines

It will clear all the lines at once which have been created.


await controller!.clearLines();

g. getLineLatLngs

We can get the line Latitude Longitude which has been created of the _selectedLine.


await controller!.getLineLatLngs(_selectedLine!);

8. Marker

a. addGalliMarker

The marker appears on the map depending on the geometry provided by the user, which is LatLng. The iconSize, iconOpacity, iconImage, iconColor mean size, opacity, image, color of the icons. The other properties we can use can be shown in the below example.


// _selectedMarker is of type Marker, and it will hold a reference to the Marker you added to the map.
if (_selectedMarker == null) {
  _selectedMarker = await controller!.addGalliMarker(const GalliMarkerOptions(
    geometry: LatLng(27.679532173752087, 85.31970941996086),
    iconAnchor: 'center ',
    iconSize: 0.5,
    iconHaloBlur: 10,
    iconHaloWidth: 2,
    iconOpacity: 0.9,
    iconOffset: Offset(0, 0.8),
    iconColor: '#0077FF',
    iconHaloColor: '#FFFFFF',
    iconImage: 'assets/images/bank.png',
    draggable: true,
  ));
}

b. removeGalliMarker

It will remove the markers if there is any marker.


await controller!.removeGalliMarker(_selectedMarker!);

c. addGalliMarkers

We can add multiple markers with properties like geometry, iconSize, iconOpacity, iconColor, iconImage, as mentioned below.


// Create a list of LatLng coordinates
List<LatLng> markerCoordinates = [
  LatLng(27.679532173752087, 85.31970941996086),
  LatLng(27.678398466065133, 85.32168961069732),
  LatLng(27.67686348105365, 85.32227904529707),
  // Add more coordinates as needed
];

// Create a list of GalliMarkerOptions using the LatLng coordinates
List<SGalliMarkerOptions> markerOptionsList =
    markerCoordinates.map((LatLng latLng) {
  return GalliMarkerOptions(
    geometry: latLng,
    iconAnchor: 'center',
    iconSize: 0.5,
    iconHaloBlur: 10,
    iconHaloWidth: 2,
    iconOpacity: 0.9,
    iconOffset: Offset(0, 0.8),
    iconColor: '#0077FF',
    iconHaloColor: '#FFFFFF',
    iconImage: 'assets/images/bank.png',
    draggable: true,
  );
}).toList();

await controller!.addGalliMarkers(markerOptionsList);

d. clearGalliMarkers

It will clear all the markers at once.


await controller!.clearGalliMarkers();

e. getGalliMarkerLatLng

We can get the longitude and latitude of the selected markers.


await controller!.getGalliMarkerLatLng(_selectedMarker!);

9. addImage

We can add an image on the map in the given geometry.


final ByteData bytes = await rootBundle.load('assets/images/doctor-2.jpg');
final Uint8List list = bytes.buffer.asUint8List();
final GalliMarkerOptions markerOptions = GalliMarkerOptions(
  geometry: LatLng(27.67784997449824, 85.31975107971293),
  iconImage: 'assetImage',
  iconSize: 0.1,
);

await controller!.addImage('assetImage', list);
await controller!.addGalliMarker(markerOptions);

10. getVisibleRegion

This method returns the boundaries of the region currently displayed in the map.


try {
  LatLngBounds visibleRegion = await controller!.getVisibleRegion();
  print("Visible Region:");
  print("Southwest: ${visibleRegion.southwest}");
  print("Northeast: ${visibleRegion.northeast}");
} catch (e) {
  print("Error: $e");
}

11. requestMyLocationLatLng

This method returns the user location.


if (controller != null) {
  LatLng? myLocation = await controller!.requestMyLocationLatLng();
  controller!.animateCamera(CameraUpdate.newLatLng(myLocation!));
}

12. toScreenLocation

This method allows you to convert a geographical location to its corresponding screen coordinates on the map. The LatLng is the geographical location.


LatLng latLng = LatLng(27.67649922688999, 85.32053625519644);
try {
  var screenPosMap = await controller!.toScreenLocation(latLng);
  print("Screen Position - X: ${screenPosMap.x}, Y: ${screenPosMap.y}");
} catch (e) {
  print("Error: $e");
}

13. toScreenLocationBatch

This method allows you to convert multiple geographical locations into screen coordinates in a batch. This can be useful when you have multiple points of interest on a map and need to work with their screen positions for various purposes.


List<LatLng> latLngsBatch = [
  LatLng(27.67649922688999, 85.32053625519644),
  LatLng(27.678398466065133, 85.32168961069732),
  LatLng(27.678113449844247, 85.3216138824787),
  // Add more LatLng coordinates as needed
];

try {
  List<Point> screenPositions = await controller!.toScreenLocationBatch(latLngsBatch);

  // Print the screen position
  for (int i = 0; i < latLngsBatch.length; i++) {
    print("LatLng: ${latLngsBatch[i]}, Screen Position: ${screenPositions[i]}");
  }
} catch (e) {
  print("Error: $e");
}

14. getMetersPerPixelAtLatitude

It returns the distance spanned by one pixel at the specified latitude and current zoom level. The distance between pixels decreases as the latitude approaches the poles.


LatLng latLng = LatLng(27.67649922688999, 85.32053625519644);
double metersPerPixel = await controller!.getMetersPerPixelAtLatitude(latLng.latitude);
debugPrint("Map long press The distance measured in meters at latitude ${latLng.latitude} is $metersPerPixel m");

15. toLatLng

It returns the geographic location (as LatLng) that corresponds to a point on the screen.


LatLng convertedLatLng = await controller!.toLatLng(Point(462.92, 1048.57));
debugPrint("Bottom press converted: ${convertedLatLng.latitude}/${convertedLatLng.longitude}");

16. setCameraBounds

It is used to restrict the camera view of the map to a specific geographic area defined by the coordinates (west, north, south, east), with an optional padding to improve the map's visual appearance and user experience. By setting camera bounds, you can control which area of the map is visible to the user and prevent them from panning outside of this region.


double west = 85.31975107971293;
double north = 27.678113449844247;
double south = 27.677681826553137;
double east = 85.32168961069732;
int padding = 25;

controller!.setCameraBounds(
    west: west,
    north: north,
    south: south,
    east: east,
    padding: padding);

17. getLayerIds

It is used to fetch and display the layer IDs present in the Mapbox map controller. It can be helpful for debugging and understanding the structure of layers in a Mapbox map.


List<String> layerIds = [];
try {
  List<dynamic> dynamicLayerIds = await controller!.getLayerIds();
  layerIds = dynamicLayerIds.map((dynamicId) => dynamicId.toString()).toList();

  for (String layerId in layerIds) {
    print("Layer ID: $layerId");
  }
} catch (e) {
  print("Error getting layer IDs: $e");
}

18. getSourceIds

Retrieve every source ids of the map as a [String] list, including the ones added internally.


List<String> sourceIds = [];
try {
  List<dynamic> dynamicSourceIds = await controller!.getSourceIds();
  sourceIds = dynamicSourceIds.map((dynamicId) => dynamicId.toString()).toList();

  for (String sourceId in sourceIds) {
    print("Source ID: $sourceId");
}
} catch (e) {
  print("Error getting source IDs: $e");
}

19. queryRenderedFeatures

It is used to query for and print information about features on a map at a specific screen coordinate, using layer IDs to filter the results.


try {
  List<dynamic> dynamicLayerIds = await controller!.getLayerIds();

  List<String> layerIds = dynamicLayerIds.map((dynamicId) => dynamicId.toString()).toList();
  double screenX = 462.92;
  double screenY = 1048.57;
  Point<double> screenPoint = Point<double>(screenX, screenY);

  List features = await controller!
      .queryRenderedFeatures(screenPoint, layerIds, null);

  if (features.isNotEmpty) {
    String featureString = features[0].toString();
    print("\nFeature: $featureString");
  }
} catch (e) {
  print("Error: $e");
}

20. queryRenderedFeaturesInRect

It allows you to query for features on a map within a defined rectangular region, using layer IDs to filter the results.


try {
  List<dynamic> dynamicLayerIds = await controller!.getLayerIds();

  List<String> layerIds = dynamicLayerIds.map((dynamicId) => dynamicId.toString()).toList();

  Rect rect = Rect.fromLTRB(0, 0, 100, 500);

  List features = await controller!
      .queryRenderedFeaturesInRect(rect, layerIds, null);
  log("feautres: $features");
  if (features.isNotEmpty) {
    String featureString = features[0].toString();
    print("\nFeature: $featureString");
  }
} catch (e) {
  print("Error: $e");
}

21. querySourceFeatures

It is designed to interact with a map controller, retrieve features from a specific data source based on defined criteria and process.


try {
  List<String> sourceIds = [];
  await controller!.getSourceIds().then((value) {
    for (dynamic data in value) {
      sourceIds.add(data.toString());
    }
    for (String sourceId in sourceIds) {
      print("Source ID: $sourceId");
    }
  });

  String sourceId = 'mapbox-location-source';
  String? sourceLayerId;
  List<dynamic>? filter = null;

  List<dynamic> features = await controller!.querySourceFeatures(sourceId, sourceLayerId, filter);

  if (features.isNotEmpty) {
    for (var feature in features) {
      String featureString = feature.toString();
      print("\nFeature from Source ID $sourceId: $featureString");
    }
  }
} catch (e) {
  print("Error: $e");
}	

22. setLayerVisibility

It retrieves and prints the layer IDs from the Mapbox controller, and then sets the visibility of each layer to true. If the setLayerVisibility is set to false, it will disappear all the layer.


List<String> layerIds = [];
try {
  List<dynamic> dynamicLayerIds = await controller!.getLayerIds();
  layerIds = dynamicLayerIds.map((dynamicId) => dynamicId.toString()).toList();

  for (String layerId in layerIds) {
    print("Layer ID: $layerId");
    await controller!.setLayerVisibility(layerId, true);
  }
} catch (e) {
  print("Error: $e");
}

23. getFilter

It is used to inspect the filters applied to layers on your Mapbox map, excluding the 'background' layer. It's useful for debugging and understanding how data is filtered and displayed on the map.


try {
  List<String> layerIds = [];
  List<dynamic> dynamicLayerIds = await controller!.getLayerIds();
  layerIds = dynamicLayerIds
      .map((dynamicId) => dynamicId.toString())
      .toList();

  for (String layerId in layerIds) { 
    // Skip layers that are not suitable for filtering
    if (layerId != 'background') {
      print("Layer ID: $layerId");

      // Fetch the filter for the current layer
      dynamic filter = await controller!.getFilter(layerId);

      // Print the filter to the console
      print('Filter for layer ID $layerId: $filter');
    }
  }
} catch (e) {
  // Handle any errors that may occur
  print("Error: $e");
}

24. setFilter

It applies filters to layers on your Mapbox map while skipping specified layers. It provides flexibility in customizing how data is displayed on the map based on your filtering criteria. The LayedIdsToSkip is the layer which is skipped, and the filter is applied to all the other layers.


try {
  List<String> layerIdsToSkip = [
    'background',
    'mapbox-location-background-layer',
    'mapbox-location-shadow-layer',
    'boundary',
    'amenity_point'
  ]; // Add the layer IDs you want to skip to this list

  List<String> layerIds = [];
  List<dynamic> dynamicLayerIds = await controller!.getLayerIds();
  layerIds = dynamicLayerIds
      .map((dynamicId) => dynamicId.toString())
      .toList();

  for (String layerId in layerIds) {
    // Skip layers that are not suitable for filtering
    if (!layerIdsToSkip.contains(layerId)) {
      print("Layer ID: $layerId");

      // Define your filter criteria
      dynamic filter = ['==', 'osm_subtype', 'nature_reserve'];

      // Set the filter for the current layer
      await controller!.setFilter(layerId, filter);
    }
  }
} catch (e) {
  // Handle any errors that may occur
  print("Error: $e");
}

25. updateMyLocationTrackingMode

It enables continuous tracking of the user's location on the map and prints their current location to the console as they move.


controller!.updateMyLocationTrackingMode(MyLocationTrackingMode.tracking);
print('Current Location: Latitude=${myLocation.latitude}, Longitude=${myLocation.longitude}');

29. updateContentInsets

It is used to update the content insets of a UI element with specified padding values and provides error handling to handle any potential issues that may arise during the update. Content insets are often used to control the spacing or margins around UI elements to achieve a desired layout and appearance.


EdgeInsets newInsets = EdgeInsets.only(
  top: 16.0,
  bottom: 16.0,
  left: 18.0,
  right: 28.0,
);

try {
  await controller!.updateContentInsets(newInsets, true);
  print('Content insets updated successfully.');
} catch (e) {
  print('Error updating content insets: $e');
}

26. invalidateAmbientCache

It is used to invalidate an ambient cache, typically to ensure that any cached data related to the ambient context is updated or cleared as needed.


try {
  // Invalidate the ambient cache
  await controller!.invalidateAmbientCache();
  print('Ambient cache invalidated successfully.');
} catch (e) {
  // Handle any errors that may occur
  print('Error invalidating ambient cache: $e');
}

27. removeLayer

It retrieves a list of dynamic layer IDs, converts them to strings, and then removes each layer from the map using the Mapbox controller. It provides a way to dynamically clear all layers from the map as needed, which can be useful in various map-related applications.


try {
  List<dynamic> dynamicLayerIds = await controller!.getLayerIds();
  layerIds = dynamicLayerIds
      .map((dynamicId) => dynamicId.toString())
      .toList();

  // Print the list of layer IDs
  for (String layerId in layerIds) {
    print("Layer ID: $layerId");
  }
} catch (e) {
  print("Error getting layer IDs: $e");
}

// Remove each layer
for (String layerId in layerIds) {
  await controller!.removeLayer(layerId);
}

28. setGalliMarkerIconAllowOverlap

It sets a configuration option for marker icons on the map, allowing them to overlap when they are close to each other.


await controller!.setGalliMarkerIconAllowOverlap(true);

33. setGalliMarkerIconIgnorePlacement

It configures a setting for marker icons on the map, indicating that they should not ignore placement rules and should adhere to positioning constraints.


await controller!.setGalliMarkerIconIgnorePlacement(false);

29. reverGeoCoding

It performs reverse geocoding to convert latitude and longitude coordinates into a location name.


String? locationString = await controller!
                .reverGeoCoding(LatLng(27.67686348105365, 85.32227904529707));

if (locationString != null) {
  print("Reverse Geocoded Location: $locationString");
} else {
  print("Reverse Geocoding failed or no location found.");
}