> For the complete documentation index, see [llms.txt](https://docs.avonnicomponents.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.avonnicomponents.com/flow/tutorials/projects/interactive-map-filtering.md).

# Interactive Map Filtering

Build a screen flow where four Avonni Metrics recount the accounts in view each time a rep pans or zooms the Avonni Map.

A field sales rep opens the flow, drags the map over the Mission District and zooms in. The four figures above the map change with every move: accounts in view, their revenue, the Hot accounts and the average revenue. The map tells the flow what area it shows, and a formula turns that into a query filter for each Metric.

<figure><img src="https://27923732-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1FUd4apB9YHgCEMUFbVb%2Fuploads%2FeZqTt48vtAKE1eRXE3WZ%2Fmaptuto-interactive-map-filtering-result.png?alt=media" alt="A screen flow with four metrics above a map of the Mission District in San Francisco: Accounts in view 9, Revenue in view 53.2 million dollars, Hot accounts 3 and Average revenue 5.9 million dollars, with eight account pins on the map."><figcaption><p>The metrics recount the accounts in view each time the rep pans or zooms.</p></figcaption></figure>

## Before you start

* Your Accounts have a billing address with **Billing Latitude** and **Billing Longitude** filled in. Salesforce fills them when the Data Integration Rule **Geocodes for Account Billing Address** is active: in Setup, open **Data Integration Rules**, activate it, then run it once to backfill existing records.
* The map must use **Type** **Leaflet**. Google Maps does not send its center or visible width back to the flow. See [Map](https://docs.avonnicomponents.com/flow/flow-components/map.md) for the differences.
* The filter in this tutorial uses `DISTANCE()`, which needs a compound location field: `BillingAddress` on Account, or a custom Geolocation field. Two separate number fields do not work (see Troubleshooting).

## Steps

{% stepper %}
{% step %}

### Create the screen flow and the metrics row

1. In Flow Builder, create a **Screen Flow** and add a **Screen** element.
2. Drag a **Section** onto the screen and give it four columns.
3. Drag an **Avonni Metric** into each column. Give each one a clear API name.
   {% endstep %}

{% step %}

### Add the map

Drag an **Avonni Map** below the section and name it `map`. The formulas below use that API name.

1. In the **Properties** tab, set **Type** to **Leaflet**.
2. In **Data Source**, choose **Query** and the **Account** object. Add a business filter if you need one (for example **Billing City** equals `San Francisco`), but never the visible-area filter.
3. In **Data Mappings**, map **Title** to Account Name, and under **Location** map **Latitude** to Billing Latitude and **Longitude** to Billing Longitude.
   {% endstep %}

{% step %}

### Create the visible-area formula

The map publishes three values as the user moves it: `{!map.centerLatitude}`, `{!map.centerLongitude}` and `{!map.visibleWidthKm}`. A text formula puts them into a SOQL condition.

1. In the **Toolbox**, click **New Resource**, choose **Formula**, name it `VisibleAreaFilter` and set **Data Type** to **Text**.
2. Paste this formula:

```
"DISTANCE(BillingAddress, GEOLOCATION(" & {!map.centerLatitude} & "," & {!map.centerLongitude} & "), 'km') < " & TEXT({!map.visibleWidthKm} / 2)
```

At run time it produces a condition such as `DISTANCE(BillingAddress, GEOLOCATION(37.76,-122.42), 'km') < 2`: keep the accounts within half the visible width of the map center, which is roughly what the screen shows.
{% endstep %}

{% step %}

### Add a formula for each segment

A metric that counts only part of what is visible needs its own formula: the same condition plus one more. For the Hot accounts metric, create a second text formula named `VisibleHotFilter`:

```
"DISTANCE(BillingAddress, GEOLOCATION(" & {!map.centerLatitude} & "," & {!map.centerLongitude} & "), 'km') < " & TEXT({!map.visibleWidthKm} / 2) & " AND Rating = 'Hot'"
```

Other segments follow the same pattern: `" AND Industry = 'Technology'"`, `" AND Type = 'Customer - Direct'"`, `" AND AnnualRevenue > 10000000"`. Values inside the condition take single quotes, the formula text takes double quotes.
{% endstep %}

{% step %}

### Point each metric at its formula

Open each Metric's Component Builder:

1. Set **Label**, then open **Primary Metric** and choose a **Format Style**.
2. On **Value**, click the query icon, then set **Object API Name** to **Account**, pick a **Field** and an **Aggregate Function**.
3. In **Filters**, switch the filter to a mapped value with its icon and select the formula. The filter then shows the formula's name.

| Label            | Format Style | Field           | Aggregate Function | Filters             |
| ---------------- | ------------ | --------------- | ------------------ | ------------------- |
| Accounts in view | Decimal      | `Id`            | Count              | `VisibleAreaFilter` |
| Revenue in view  | Currency     | `AnnualRevenue` | Sum                | `VisibleAreaFilter` |
| Hot accounts     | Decimal      | `Id`            | Count              | `VisibleHotFilter`  |
| Average revenue  | Currency     | `AnnualRevenue` | Average            | `VisibleAreaFilter` |

<figure><img src="https://27923732-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1FUd4apB9YHgCEMUFbVb%2Fuploads%2FVNfpg632060iiZ6hIOTx%2Fmaptuto-interactive-map-filtering-metric-filter.png?alt=media" alt="The Properties tab of a Metric labeled Hot accounts: Format Style Decimal, Value counting Account Id with the Filters set to the mapped formula Visible Hot Filter." width="320"><figcaption><p>Each metric reads its query filter from a formula, through Mapped.</p></figcaption></figure>

{% hint style="warning" %}
Leave the map's own query without the visible-area formula. Filtered by what it shows, the map has nothing loaded beyond its edges, so every pan opens on an empty area.
{% endhint %}
{% endstep %}

{% step %}

### Save and test

Save, then click **Debug** or **Run**. The map opens with every account pin. Zoom into one neighborhood: the four metrics drop to the accounts in that area. Zoom out and they grow again.
{% endstep %}
{% endstepper %}

## Troubleshooting

<details>

<summary>The metrics are empty or show an error when the flow opens</summary>

The map publishes its center only after it has drawn its first view, so the formula briefly has no coordinates. Pan or zoom once. To give the first load a valid filter, wrap the formula: `IF(ISBLANK({!map.centerLatitude}), "Id != null", <the formula above>)`.

</details>

<details>

<summary>Error "Cannot read properties of undefined" at run time</summary>

The formula produced an incomplete SOQL condition: a missing quote, a trailing `&`, or a map API name that does not match the one in the formula. Copy the formula again and check that the map is named `map`.

</details>

<details>

<summary>A metric counts a few more accounts than the pins on screen</summary>

The filter is a circle around the center whose radius is the visible width, and the screen is a rectangle. A few accounts just off screen fall inside the circle. Pan or zoom out to see them.

</details>

<details>

<summary>My object stores latitude and longitude in two number fields</summary>

`DISTANCE()` does not accept them. Add a Geolocation field to the object, fill it from the two number fields, and replace `BillingAddress` with its API name in every formula, for example `DISTANCE(Store_Location__c, GEOLOCATION(...`.

</details>

## Related tutorials

* [Add Search and Filters to a Map](https://docs.avonnicomponents.com/flow/tutorials/components/map/add-search-and-filters.md): let the rep narrow the pins with menus instead of the viewport.
* [Filter a Data Table or Map by the current record](https://docs.avonnicomponents.com/flow/tutorials/tips-and-tricks/filter-a-data-table-or-map-by-the-current-record.md): the same Mapped filter idea, driven by `{!recordId}`.
* [Plan a Route from the Map](https://docs.avonnicomponents.com/flow/tutorials/components/map/plan-a-route.md): turn the accounts in view into a day of visits.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.avonnicomponents.com/flow/tutorials/projects/interactive-map-filtering.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
