### Map Matching API Request Example
Source: https://docs.mapatlas.xyz/overview/directions/mapMatch
This snippet shows an example of a GET request to the `/map-matching/` API endpoint, including the required API token and the JSON body containing shape data, costing, and shape matching preferences.
```http
GET /map-matching/?token=YOUR_API_TOKEN
```
```json
{
"shape": [
{ "lat": 39.983841, "lon": -76.735741, "type": "break" },
{ "lat": 39.983704, "lon": -76.735298, "type": "via" },
{ "lat": 39.983578, "lon": -76.734848, "type": "via" },
{ "lat": 39.983551, "lon": -76.734253, "type": "break" },
{ "lat": 39.983555, "lon": -76.734116, "type": "via" },
{ "lat": 39.983589, "lon": -76.733315, "type": "via" },
{ "lat": 39.983719, "lon": -76.732445, "type": "via" },
{ "lat": 39.983818, "lon": -76.731712, "type": "via" },
{ "lat": 39.983776, "lon": -76.731506, "type": "via" },
{ "lat": 39.983696, "lon": -76.731369, "type": "break" }
],
"costing": "auto",
"shape_match": "map_snap"
}
```
--------------------------------
### Initialize Map: Google Maps vs. Mapmetrics GL JS
Source: https://docs.mapatlas.xyz/overview/sdk/examples/google-maps-migration-guide
Compares the initialization of a map using Google Maps JavaScript API and Mapmetrics GL JS. Both examples require specific configurations for container, center, and zoom level. Mapmetrics GL JS also requires an access token and style URL.
```html
```
```html
```
--------------------------------
### Complete React Example with MapMetrics Map
Source: https://docs.mapatlas.xyz/overview/sdk/examples/simple-map-npm
A comprehensive React component that initializes and manages a MapMetrics map. It uses `useEffect` for map setup and cleanup, and `useRef` to manage the map container and instance. This example ensures the map is properly mounted and removed with the component lifecycle.
```javascript
import React, { useEffect, useRef } from "react";
import mapmetricsgl from "@mapmetrics/mapmetrics-gl";
import "@mapmetrics/mapmetrics-gl/dist/mapmetrics-gl.css";
const App = () => {
const mapContainerRef = useRef(null);
const mapRef = useRef(null);
const accessToken = ``;
useEffect(() => {
if (!mapContainerRef.current || mapRef.current) return;
const map = new mapmetricsgl.Map({
container: mapContainerRef.current,
style: `${accessToken}`,
center: [2.349902, 48.852966],
zoom: 11,
minZoom: 1,
maxZoom: 24,
attributionControl: false,
cooperativeGestures: true,
});
mapRef.current = map;
return () => {
map.remove();
mapRef.current = null;
};
}, []);
return (
);
};
export default App;
```
--------------------------------
### Initialize MapView in MainActivity (Kotlin)
Source: https://docs.mapatlas.xyz/overview/sdk/android-native/getting-started
This Kotlin code initializes the MapView in your Android Activity. It handles the map's lifecycle methods (onCreate, onStart, onResume, etc.) and sets the map style, either using a predefined style or from a provided file name if an API key is not properly configured. Ensure you have the necessary API key setup.
```kotlin
class SimpleMapActivity : AppCompatActivity() {
// Declare a variable for MapView
private lateinit var mapView: MapView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
onBackPressedDispatcher.addCallback(this, object: OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
// activity uses singleInstance for testing purposes
// code below provides a default navigation when using the app
NavUtils.navigateHome(this@SimpleMapActivity)
}
})
setContentView(R.layout.activity_map_simple)
mapView = findViewById(R.id.mapView)
mapView.onCreate(savedInstanceState)
mapView.getMapAsync {
val key = ApiKeyUtils.getApiKey(applicationContext)
if (key == null || key == "YOUR_API_KEY_GOES_HERE") {
it.setStyle(
Style.Builder().fromUri(fileName)
)
} else {
val styles = Style.getPredefinedStyles()
if (styles.isNotEmpty()) {
val styleUrl = styles[0].url
it.setStyle(Style.Builder().fromUri(styleUrl))
}
}
}
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
}
```
--------------------------------
### Install MapMetrics-gl SDK via NPM (Bash)
Source: https://docs.mapatlas.xyz/overview/sdk/mapmetrics
Installs the MapMetrics-gl library using the NPM package manager. This is recommended for production environments to ensure better version control.
```bash
npm i @mapmetrics/mapmetrics-gl
```
--------------------------------
### Install MapMetrics-gl SDK via Yarn (Bash)
Source: https://docs.mapatlas.xyz/overview/sdk/mapmetrics
Installs the MapMetrics-gl library using the Yarn package manager. This is recommended for production environments to ensure better version control.
```bash
yarn add @mapmetrics/mapmetrics-gl
```
--------------------------------
### Example Podfile for MapMetrics-iOS
Source: https://docs.mapatlas.xyz/overview/sdk/ios-native/mapmetrics-ios-add-Map-Basic-guide
A complete example of a Podfile for an iOS project using the MapMetrics-iOS library, including platform specification, framework usage, version targeting, and the sandbox fix.
```ruby
platform :ios, '12.0'
target 'YourApp' do
use_frameworks!
pod 'MapMetrics-iOS', '~> 0.0.1'
post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings['ENABLE_USER_SCRIPT_SANDBOXING'] = 'NO'
end
end
end
end
```
--------------------------------
### Install Dependencies via CocoaPods
Source: https://docs.mapatlas.xyz/overview/sdk/ios-native/mapmetrics-ios-add-Map-Basic-guide
Command to execute after updating your Podfile to install the specified CocoaPods dependencies.
```bash
pod install
```
--------------------------------
### Set up and animate image source with Kotlin
Source: https://docs.mapatlas.xyz/overview/sdk/android-native/styling/animated-image-source
This snippet shows the initial setup of an animated image source using Kotlin. It defines a geographic quad, creates an ImageSource with an initial drawable, adds a RasterLayer, and starts a RefreshImageRunnable to handle updates. Dependencies include Mapbox SDK classes and Android's Handler.
```kotlin
val quad = LatLngQuad(
LatLng(46.437, -80.425),
LatLng(46.437, -71.516),
LatLng(37.936, -71.516),
LatLng(37.936, -80.425)
)
val imageSource = ImageSource(ID_IMAGE_SOURCE, quad, R.drawable.southeast_radar_0)
val layer = RasterLayer(ID_IMAGE_LAYER, ID_IMAGE_SOURCE)
map.setStyle(
Style.Builder()
.fromUri(TestStyles.AMERICANA)
.withSource(imageSource)
.withLayer(layer)
) { style: Style? ->
runnable = RefreshImageRunnable(imageSource, handler)
runnable?.let {
handler.postDelayed(it, 100)
}
}
```
--------------------------------
### Install MapMetrics-iOS using CocoaPods
Source: https://docs.mapatlas.xyz/overview/sdk/ios-native/mapmetrics-ios-add-Map-Basic-guide
Instructions for adding the MapMetrics-iOS library to your project's Podfile. Supports version targeting and direct git repository installation.
```ruby
target 'YourApp' do
pod 'MapMetrics-iOS', '~> 0.0.1' # Use the latest version
# OR
pod 'MapMetrics-iOS', :git => 'https://github.com/MapMetrics/MapMetrics-iOS', :tag => '0.0.1'
end
```
--------------------------------
### Install MapMetrics-gl Package with NPM
Source: https://docs.mapatlas.xyz/overview/sdk/examples/simple-map-npm
Installs the MapMetrics-gl package into your project using npm. This is the first step to integrate MapMetrics maps into your web application.
```bash
npm install @mapmetrics/mapmetrics-gl
```
--------------------------------
### Swift: Setup Map Clusters and Layers
Source: https://docs.mapatlas.xyz/overview/sdk/ios-native/mapmetrics-ios-Map-add-Clusters
This Swift function, `setupClusters`, configures map clusters by fetching GeoJSON data from a URL, creating a shape source with clustering enabled, and adding multiple layers to visualize cluster counts and individual points. It includes error handling for network requests and style access. The `addClusterLayers` helper function defines the visual properties for cluster and point layers.
```swift
func setupClusters() {
print("🟢 Starting cluster setup")
guard let style = mapView.style else {
print("🔴 CRITICAL ERROR: Map style is nil")
return
}
guard let url = URL(string: "https://cdn.mapmetrics-atlas.net/Images/heatmap.geojson") else {
print("🔴 ERROR: Invalid GeoJSON URL")
return
}
let task = URLSession.shared.dataTask(with: url) { data, response, error in
if let data = data {
print("✅ GeoJSON Size: \(data.count) bytes")
if let geoJSON = String(data: data, encoding: .utf8) {
print("📦 Preview GeoJSON:\n\(geoJSON.prefix(500))")
}
} else {
print("❌ Failed to fetch GeoJSON: \(error?.localizedDescription ?? "Unknown error")")
}
}
task.resume()
if let layer = style.layer(withIdentifier: "earthquakes-heat") as? MLNVectorStyleLayer {
print("Heatmap filter: \(String(describing: layer.predicate))")
}
do {
// Create source without custom cluster properties first
let source = MLNShapeSource(
identifier: "clusteredEarthquakes",
url: url,
options: [
.clustered: true,
.clusterRadius: 30
]
)
if let shapeCollection = source.shape as? MLNShapeCollectionFeature {
var minLat = 90.0
var maxLat = -90.0
var minLon = 180.0
var maxLon = -180.0
for feature in shapeCollection.shapes {
if let point = feature as? MLNPointFeature {
let coord = point.coordinate
minLat = min(minLat, coord.latitude)
maxLat = max(maxLat, coord.latitude)
minLon = min(minLon, coord.longitude)
maxLon = max(maxLon, coord.longitude)
}
// Optionally handle more geometry types like MGLPolylineFeature or MGLPolygonFeature here
}
let sw = CLLocationCoordinate2D(latitude: minLat, longitude: minLon)
let ne = CLLocationCoordinate2D(latitude: maxLat, longitude: maxLon)
let bounds = MLNCoordinateBounds(sw: sw, ne: ne)
let camera = mapView.cameraThatFitsCoordinateBounds(bounds, edgePadding: .init(top: 40, left: 20, bottom: 40, right: 20))
mapView.setCamera(camera, animated: true)
}
style.addSource(source)
print("🟢 Source added successfully")
// Create and add layers...
try addClusterLayers(source: source, to: style)
} catch {
print("🔴 ERROR: \(error.localizedDescription)")
if let nsError = error as NSError? {
print("User Info: \(nsError.userInfo)")
}
}
}
private func addClusterLayers(source: MLNShapeSource, to style: MLNStyle) throws {
// Cluster layer
let clusterLayer = MLNCircleStyleLayer(identifier: "clusters", source: source)
clusterLayer.circleColor = NSExpression(format: "mgl_step:from:stops:(point_count, %@, %@)",
UIColor.systemTeal,
[100: UIColor.systemYellow, 750: UIColor.systemPink])
clusterLayer.circleRadius = NSExpression(format: "mgl_step:from:stops:(point_count, 20, %@)",
[100: 30, 750: 40])
clusterLayer.predicate = NSPredicate(format: "point_count >= 0")
style.addLayer(clusterLayer)
// Count layer
let countLayer = MLNSymbolStyleLayer(identifier: "cluster-count", source: source)
countLayer.text = NSExpression(format: "CAST(point_count_abbreviated, 'NSString')")
countLayer.textFontNames = NSExpression(forConstantValue: ["Noto Sans Medium"])
countLayer.textFontSize = NSExpression(forConstantValue: 12)
countLayer.predicate = NSPredicate(format: "point_count >= 0")
style.addLayer(countLayer)
// Unclustered point layer
let pointLayer = MLNCircleStyleLayer(identifier: "unclustered-point", source: source)
pointLayer.circleColor = NSExpression(forConstantValue: UIColor.systemBlue)
pointLayer.circleRadius = NSExpression(forConstantValue: 4)
pointLayer.circleStrokeWidth = NSExpression(forConstantValue: 1)
pointLayer.circleStrokeColor = NSExpression(forConstantValue: UIColor.white)
pointLayer.predicate = NSPredicate(format: "point_count == nil")
style.addLayer(pointLayer)
}
```
--------------------------------
### Replace mapbox-gl CSS class with mapmetrics-ctrl
Source: https://docs.mapatlas.xyz/overview/sdk/mapbox-migration-guide
This example demonstrates how to update CSS class names to align with the mapmetrics library. The change is from `mapboxgl-ctrl` to `mapmetrics-ctrl` for buttons or other control elements. This is a straightforward text replacement in HTML/CSS.
```html
```
```html
```
--------------------------------
### Setup MapView in ViewController Swift
Source: https://docs.mapatlas.xyz/overview/sdk/ios-native/mapmetrics-ios-Map-add%20markers
This code snippet demonstrates how to initialize and configure an MLNMapView within a ViewController in Swift. It sets the map's initial center, zoom level, and assigns the ViewController as the map view's delegate. Ensure the MapMetrics SDK is added to your project.
```swift
class ViewController: UIViewController, MLNMapViewDelegate {
var mapView: MLNMapView!
var selectedAnnotation: MLNPointAnnotation?
var isMarkerSelected = false
override func viewDidLoad() {
super.viewDidLoad()
mapView = MLNMapView(
frame: view.bounds,
styleURL: URL(string: "")
)
mapView.delegate = self
view.addSubview(mapView)
mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
mapView.delegate = self
let center = CLLocationCoordinate2D(latitude: 20.0, longitude: 0.0)
mapView.setCenter(center, zoomLevel: 2, animated: false)
view.addSubview(mapView)
}
}
```
--------------------------------
### Example PMTiles Style JSON
Source: https://docs.mapatlas.xyz/overview/sdk/android-native/data/PMTiles
This is an example style JSON file that utilizes PMTiles vector sources. This style is from the wipfli/foursquare-os-places-pmtiles repository and demonstrates how a style can be constructed using only PMTiles, simplifying tile server requirements.
```json
{
"version": 8,
"name": "Foursquare OS Places",
"sources": {
"composite": {
"type": "vector",
"url": "pmtiles://https://raw.githubusercontent.com/wipfli/foursquare-os-places-pmtiles/refs/heads/main/foursquare-os-places.pmtiles"
}
},
"layers": [
// ... layer definitions using the 'composite' source ...
]
}
```
--------------------------------
### ScaleControl API
Source: https://docs.mapatlas.xyz/overview/API/classes/ScaleControl
Documentation for the ScaleControl class, including its constructor, methods, and usage examples.
```APIDOC
## ScaleControl
### Description
A `ScaleControl` control displays the ratio of a distance on the map to the corresponding distance on the ground.
### Example
```typescript
let scale = new ScaleControl({
maxWidth: 80,
unit: 'imperial'
});
map.addControl(scale);
scale.setUnit('metric');
```
### Implements
* `IControl`
### Constructors
#### Constructor
> **new ScaleControl**(`options?`: `ScaleControlOptions`): `ScaleControl`
##### Parameters
- `options` (`ScaleControlOptions`) - Optional - The control's options
##### Returns
`ScaleControl`
### Methods
#### getDefaultPosition()
> **getDefaultPosition**(): `ControlPosition`
##### Description
Optionally provide a default position for this control. If this method is implemented and Map#addControl is called without the `position` parameter, the value returned by getDefaultPosition will be used as the control's position.
##### Returns
`ControlPosition` - A control position, one of the values valid in addControl.
##### Implementation of
`IControl`.`getDefaultPosition`
#### onAdd()
> **onAdd**(`map`: `Map`): `HTMLElement`
##### Description
Register a control on the map and give it a chance to register event listeners and resources. This method is called by Map#addControl internally.
##### Parameters
- `map` (`Map`) - The Map this control will be added to
##### Returns
`HTMLElement` - The control's container element. This should be created by the control and returned by onAdd without being attached to the DOM: the map will insert the control's element into the DOM as necessary.
##### Implementation of
`IControl`.`onAdd`
#### onRemove()
> **onRemove**(): `void`
##### Description
Unregister a control on the map and give it a chance to detach event listeners and resources. This method is called by Map#removeControl internally.
##### Returns
`void`
##### Implementation of
`IControl`.`onRemove`
#### setUnit()
> **setUnit**(`unit`: `Unit`): `void`
##### Description
Set the scale's unit of the distance
##### Parameters
- `unit` (`Unit`) - Unit of the distance (`'imperial'`, `'metric'` or `'nautical'`).
##### Returns
`void`
```
--------------------------------
### Import MapMetrics-gl SDK in JavaScript (JS)
Source: https://docs.mapatlas.xyz/overview/sdk/mapmetrics
Imports the MapMetrics-gl library and its associated CSS file within a JavaScript module. This is used after installing via NPM or Yarn.
```js
import mapmetricsgl from "mapmetrics-gl";
import "mapmetrics-gl/dist/mapmetrics-gl.css";
```
--------------------------------
### Create Flutter Project and Navigate
Source: https://docs.mapatlas.xyz/overview/sdk/examples/flutter-setup
This snippet demonstrates the basic commands to create a new Flutter project and navigate into its directory. It's the initial step for any Flutter development.
```bash
flutter create mapmetrics_demo
cd mapmetrics_demo
```
--------------------------------
### Install MapMetrics-gl SDK via CDN (HTML)
Source: https://docs.mapatlas.xyz/overview/sdk/mapmetrics
Includes the MapMetrics-gl JavaScript and CSS files directly from the CDN into the `` of an HTML file. This method is suitable for quick prototypes and demos.
```html
```
--------------------------------
### Autocomplete API Request (Bash)
Source: https://docs.mapatlas.xyz/overview/geocoder/autocomplete
This example demonstrates how to make a GET request to the Autocomplete API using bash. It includes essential parameters like the search text, boundary information (circle latitude, longitude, and radius), and the required API token. Ensure to replace 'YOUR_API_KEY' with your actual token.
```bash
GET https://gateway.mapmetrics-atlas.net/autocomplete/?text=YMCA&boundary.circle.lon=-79.186484&boundary.circle.lat=43.818156&boundary.circle.radius=35&token=YOUR_API_KEY
```
--------------------------------
### Complete HTML Example for Map
Source: https://docs.mapatlas.xyz/overview/sdk/examples/simple-map-cdn
A full HTML document demonstrating the integration of MapMetrics GL using CDN links. It includes the necessary head meta tags, CDN imports for CSS and JS, basic page styling, a map container div, and JavaScript for map initialization with an access token, style URL, zoom, center, and RTL text plugin.
```html
```
--------------------------------
### Create Webpage with Mapmetrics GL JS
Source: https://docs.mapatlas.xyz/overview/sdk/examples/google-maps-migration-guide
Sets up a basic HTML page with Mapmetrics GL JS integrated, including CSS and JavaScript to initialize a map. Requires a Mapmetrics access token. The map is displayed in a div with the ID 'map'.
```html
```
--------------------------------
### Setup Heatmap Layer in Swift
Source: https://docs.mapatlas.xyz/overview/sdk/ios-native/mapmetrics-ios-Map-add-Heatmap
This Swift function configures and adds a heatmap layer to a map. It removes any pre-existing layers with the same identifier, creates a new MLNShapeSource from a GeoJSON URL, and then defines the visual properties of the MLNHeatmapStyleLayer, including weight, intensity, color, radius, and opacity. Finally, it inserts the layer into the map's style. Dependencies include the Mapbox SDK for iOS.
```swift
func setupHeatmap() {
guard let style = mapView.style else {
print("🔴 Map style not available")
return
}
// 1. Remove any existing source/layer to avoid duplicates
if let existingSource = style.source(withIdentifier: "earthquakes") {
style.removeSource(existingSource)
}
if let existingLayer = style.layer(withIdentifier: "earthquakes-heat") {
style.removeLayer(existingLayer)
}
// 2. Create the source with proper options
let url = URL(string: "https://cdn.mapmetrics-atlas.net/Images/heatmap.geojson")!
let source: MLNShapeSource
do {
source = MLNShapeSource(
identifier: "earthquakes",
url: url,
options: [.clustered: false] // Important for heatmap
)
style.addSource(source)
print("🟢 Heatmap source added successfully")
// 3. Create the heatmap layer with proper configuration
let heatmap = MLNHeatmapStyleLayer(identifier: "earthquakes-heat", source: source)
// Weight based on magnitude with exponential scaling
heatmap.heatmapWeight = NSExpression(
forMLNInterpolating: NSExpression(forKeyPath: "mag"),
curveType: .exponential,
parameters: NSExpression(forConstantValue: 1.5),
stops: NSExpression(forConstantValue: [
0: 0,
1: 0.2,
3: 0.4,
5: 1.0
])
)
// Dynamic intensity based on zoom level
heatmap.heatmapIntensity = NSExpression(
forMLNInterpolating: .zoomLevelVariable,
curveType: .linear,
parameters: nil,
stops: NSExpression(forConstantValue: [
0: 0.5,
5: 1.5,
10: 3.0
])
)
// Color gradient from cool to hot
heatmap.heatmapColor = NSExpression(
forMLNInterpolating: NSExpression(forVariable: "heatmapDensity"),
curveType: .linear,
parameters: nil,
stops: NSExpression(forConstantValue: [
0: UIColor.blue.withAlphaComponent(0),
0.2: UIColor.blue,
0.4: UIColor.cyan,
0.6: UIColor.green,
0.8: UIColor.yellow,
1.0: UIColor.red
])
)
// Radius that changes with zoom
heatmap.heatmapRadius = NSExpression(
forMLNInterpolating: .zoomLevelVariable,
curveType: .linear,
parameters: nil,
stops: NSExpression(forConstantValue: [
0: 5,
5: 10,
10: 20
])
)
heatmap.heatmapOpacity = NSExpression(forConstantValue: 0.8)
heatmap.isVisible = false // Start hidden
// 4. Add the layer in the correct position (above base but below labels)
if let waterLayer = style.layer(withIdentifier: "water") {
style.insertLayer(heatmap, above: waterLayer)
} else {
style.addLayer(heatmap)
}
print("🟢 Heatmap layer added successfully")
}
}
```
--------------------------------
### Filter by data type (API Request Example)
Source: https://docs.mapatlas.xyz/overview/geocoder/forwardgeocode
This example illustrates how to filter search results based on the type of place being searched for, using the 'layers' parameter. You can specify a comma-separated list of layers. The example shows a request to search for streets and venues.
```text
GET /forward-geocode/?token=YOUR_TOKEN&text=YMCA&layers=street,venue
```
--------------------------------
### Create MapMetrics Flutter Widget
Source: https://docs.mapatlas.xyz/overview/sdk/examples/flutter-setup
This Dart snippet illustrates how to create a basic map widget using the `MapMetrics` Flutter package. It includes setting the map style URL, handling map creation events, and defining the initial camera position. Remember to replace placeholder values with your actual API key and style ID.
```dart
import 'package:flutter/material.dart';
import 'package:mapmetrics/mapmetrics.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'MapMetrics Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MapScreen(),
);
}
}
class MapScreen extends StatefulWidget {
@override
_MapScreenState createState() => _MapScreenState();
}
class _MapScreenState extends State {
MapMetricsController? mapController;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('MapMetrics Atlas Map'),
),
body: MapMetrics(
styleUrl: 'https://gateway.mapmetrics.org/styles/YOUR_STYLE_ID?token=YOUR_API_KEY',
onMapCreated: (MapMetricsController controller) {
setState(() {
mapController = controller;
});
},
initialCameraPosition: CameraPosition(
target: LatLng(40.7128, -74.0060), // New York City
zoom: 10.0,
),
),
);
}
}
```
--------------------------------
### Filter by data source (API Request Example)
Source: https://docs.mapatlas.xyz/overview/geocoder/forwardgeocode
This example shows how to filter search results to include only data from specific sources. It uses the 'sources' parameter, accepting a comma-separated list of source short names. The example demonstrates fetching results solely from OpenAddresses.
```text
GET /search?token=YOUR_TOKEN&text=YMCA&sources=oa
```
--------------------------------
### Configure Map Metrics with Dart
Source: https://docs.mapatlas.xyz/overview/sdk/examples/flutter-setup
Demonstrates how to configure MapMetrics in Dart, specifying the map's style URL, initial camera position (including target coordinates, zoom, bearing, and tilt), and event handlers for map creation, clicks, and style loading.
```dart
MapMetrics(
styleUrl: 'your_style_url',
initialCameraPosition: CameraPosition(
target: LatLng(lat, lng),
zoom: zoom,
bearing: bearing,
tilt: tilt,
),
onMapCreated: (controller) {
// Handle map creation
},
onMapClick: (point, coordinates) {
// Handle map clicks
},
onStyleLoaded: () {
// Handle style loading
},
)
```
--------------------------------
### Initialize and Display 3D Buildings Map (JavaScript)
Source: https://docs.mapatlas.xyz/overview/sdk/examples/3d-building
This snippet demonstrates how to initialize a MapMetrics Atlas map, add a vector tile source for 3D buildings, and configure a fill-extrusion layer to render them. It includes event listeners for map load, movement, and feature interaction.
```html
3D Buildings
3D Buildings
Buildings: 0
Status: Loading...
```
--------------------------------
### Configure Android Compile and Min SDK Versions
Source: https://docs.mapatlas.xyz/overview/sdk/examples/flutter-setup
This Gradle snippet specifies the `compileSdkVersion` and `minSdkVersion` in the `build.gradle` file for an Android application. Ensure these versions meet the requirements of your project and the MapMetrics SDK.
```gradle
android {
compileSdkVersion 33
defaultConfig {
minSdkVersion 21
targetSdkVersion 33
}
}
```
--------------------------------
### Source Methods - Example Usage
Source: https://docs.mapatlas.xyz/overview/API/interfaces/Source
Illustrates the usage of key methods within the `Source` interface, such as loading and aborting tiles, checking tile existence, and managing source lifecycle events.
```typescript
// Example of loading a tile
const source: Source = ...;
const tile: Tile = ...;
source.loadTile(tile).then(() => {
console.log('Tile loaded successfully');
}).catch((error) => {
console.error('Error loading tile:', error);
});
// Example of aborting a tile
source.abortTile?.(tile);
// Example of checking if a tile exists
const tileExists = source.hasTile?.(tileID);
// Example of firing an event
source.fire(new Event('data', { detail: { dataType: 'source', sourceDataType: 'metadata' } }));
```
--------------------------------
### LngLatLike Type Definition and Examples (TypeScript)
Source: https://docs.mapatlas.xyz/overview/API/type-aliases/LngLatLike
Demonstrates the LngLatLike type definition and provides examples of its usage in TypeScript. This type allows for flexible representation of geographic coordinates.
```typescript
let v1 = new LngLat(-122.420679, 37.772537);
let v2 = [-122.420679, 37.772537];
let v3 = {lon: -122.420679, lat: 37.772537};
```
--------------------------------
### Initialize Map with Mapmetrics GL JS (HTML)
Source: https://docs.mapatlas.xyz/overview/sdk/examples/google-maps-migration-guide
This snippet shows the basic HTML structure required to embed an interactive map using Mapmetrics GL JS. It includes linking the necessary CSS and JavaScript libraries, basic styling for the map container, and the JavaScript code to initialize the map with an access token, style, zoom level, and center coordinates.
```html
```
--------------------------------
### Isochrone Service Request Example (JSON)
Source: https://docs.mapatlas.xyz/overview/directions/isochrone
An example of a JSON request body for the isochrone service. It specifies a single location, the 'pedestrian' costing model, and a 15-minute contour with a red color. The service returns GeoJSON.
```json
{
"locations": [{"lat": 40.744014, "lon": -73.990508}],
"costing": "pedestrian",
"contours": [{"time": 15.0, "color": "ff0000"}]
}
```
--------------------------------
### Set iOS Platform Version in Podfile
Source: https://docs.mapatlas.xyz/overview/sdk/examples/flutter-setup
This Ruby snippet specifies the minimum deployment target for iOS in the `Podfile`. Ensure the `platform` version is set appropriately for your project's requirements.
```ruby
platform :ios, '12.0'
```
--------------------------------
### Autocomplete API Response Example (JSON)
Source: https://docs.mapatlas.xyz/overview/geocoder/autocomplete
This is an example of a successful response from the Autocomplete API. It returns a GeoJSON FeatureCollection containing a list of features, where each feature represents a suggested place with its geometry (coordinates) and properties (name, country, region, locality, label).
```json
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-78.861037, 43.900526]
},
"properties": {
"name": "Durham Family YMCA",
"country": "Canada",
"region": "Ontario",
"locality": "Oshawa",
"label": "Durham Family YMCA, Oshawa, ON, Canada"
}
}
]
}
```
--------------------------------
### Initialize Map with 3D Buildings and Shadows - JavaScript
Source: https://docs.mapatlas.xyz/overview/sdk/examples/3d-buildingWithShadow
Initializes a MapMetrics Atlas map with a specified style, center, zoom, pitch, and bearing. It then adds a vector tile source for 3D buildings and configures a 'fill-extrusion' layer to render them. Shadow casting is enabled by default and can be controlled via UI elements.
```javascript
const token = `YOUR_TOKEN`;
// Initialize map with the MapMetrics Atlas style
const map = new mapmetricsgl.Map({
container: "map",
style: `https://gateway.mapmetrics-atlas.net/styles/?fileName=${token}`,
center: [5.47, 51.49], // Center of your building data
zoom: 16,
pitch: 60,
bearing: -30,
});
let shadowsEnabled = true;
let currentAzimuth = 180;
let currentAltitude = 45;
let currentIntensity = 50; // Shadow intensity as percentage (0=white, 100=black)
map.on("load", () => {
console.log("Map loaded");
document.getElementById("status").textContent = "Map loaded";
// Add the 3D buildings source
map.addSource("buildings", {
type: "vector",
tiles: [
"https://building.mapmetrics-atlas.net/data/buildings/{z}/{x}/{y}.pbf",
],
minzoom: 13,
maxzoom: 16,
});
// Add 3D buildings layer
map.addLayer({
id: "buildings-3d",
type: "fill-extrusion",
source: "buildings",
"source-layer": "building",
paint: {
"fill-extrusion-color": "#aaa",
"fill-extrusion-height": [
"case",
["has", "height"],
["get", "height"],
```
--------------------------------
### Get Current Camera Position in Dart
Source: https://docs.mapatlas.xyz/overview/sdk/examples/flutter-basic-map
Asynchronously retrieves the current camera position, including zoom level and target coordinates. Returns a CameraPosition object or null if the map controller is not ready. Use this to get the map's current viewport.
```dart
void _getCurrentPosition() async {
CameraPosition? position = await mapController?.getCameraPosition();
if (position != null) {
print('Current zoom: ${position.zoom}');
print('Current center: ${position.target}');
}
}
```
--------------------------------
### Complete MapMetrics Map with Default Marker (HTML/JS)
Source: https://docs.mapatlas.xyz/overview/sdk/examples/add-a-marker
A full HTML and JavaScript example demonstrating how to initialize a MapMetrics map and add a default marker. Includes necessary CSS and JS includes for the MapMetrics-gl library. Requires an access token for map style.
```html
```