> ## Documentation Index
> Fetch the complete documentation index at: https://docs.radar.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Build store locators

> Build a location finder that searches your stores, branches, or ATMs near an address or the user's position and shows a matching list and map.

By the end of this guide, you will have a location finder in a web page. A visitor types an address (no location permission needed) or shares their position, sees the nearest locations in a list and on a map, selects one, and sees the driving distance and time.

## Complete example

The JavaScript tab is the whole locator in one HTML page, and the other tabs run the same address search and nearby search in a native app.

```html JavaScript theme={null}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Find a location</title>
    <link href="https://js.radar.com/maps/v1.2.0/radar-maps.css" rel="stylesheet">
    <link href="https://js.radar.com/autocomplete/v1.2.0/radar-autocomplete.css" rel="stylesheet">
    <script src="https://js.radar.com/v5.3.0/radar.min.js"></script>
    <script src="https://js.radar.com/maps/v1.2.0/radar-maps.min.js"></script>
    <script src="https://js.radar.com/autocomplete/v1.2.0/radar-autocomplete.min.js"></script>
    <style>
      body { margin: 0; font-family: system-ui, sans-serif; }
      .locator { display: flex; height: 100vh; }
      .panel { width: 360px; padding: 16px; box-sizing: border-box; overflow-y: auto; }
      .map-wrap { flex: 1; }
      #results { list-style: none; margin: 0; padding: 0; }
      #results button {
        display: block; width: 100%; padding: 12px 0; border: 0;
        border-bottom: 1px solid #ddd; background: none;
        text-align: left; font: inherit; cursor: pointer;
      }
      #results button[aria-current="true"] { font-weight: 600; }
      .distance, .detail { color: #555; }

      /* Stack the list above the map on narrow screens. */
      @media (max-width: 700px) {
        .locator { flex-direction: column; }
        .panel { width: 100%; height: 50vh; }
        .map-wrap { flex: none; height: 50vh; }
      }
    </style>
  </head>

  <body>
    <div class="locator">
      <div class="panel">
        <div id="autocomplete"></div>
        <p><button id="use-location" type="button">Use my location</button></p>
        <p id="status" role="status" aria-live="polite">Search by address, city, or postal code.</p>
        <ul id="results"></ul>
      </div>
      <div class="map-wrap">
        <div id="map" style="width: 100%; height: 100%;"></div>
      </div>
    </div>

    <script>
      const TAG = 'store';
      const RADIUS_METERS = 10000;
      const LIMIT = 10;

      const statusEl = document.getElementById('status');
      const resultsEl = document.getElementById('results');
      let searchCount = 0;

      Radar.initialize('prj_test_pk_...');

      // With no center, the map starts at an estimate of the visitor's area from their IP address.
      const map = Radar.ui.map({ container: 'map', style: 'radar-default-v1' });

      function setStatus(message) {
        statusEl.textContent = message;
      }

      // Straight-line distance in miles between two { latitude, longitude } points.
      function straightLineMiles(a, b) {
        const toRadians = (degrees) => (degrees * Math.PI) / 180;
        const dLat = toRadians(b.latitude - a.latitude);
        const dLng = toRadians(b.longitude - a.longitude);
        const h = Math.sin(dLat / 2) ** 2
          + Math.cos(toRadians(a.latitude)) * Math.cos(toRadians(b.latitude)) * Math.sin(dLng / 2) ** 2;
        return 3958.8 * 2 * Math.asin(Math.sqrt(h));
      }

      // Convert a Radar geofence into the shape the list and the map both use.
      function toLocation(geofence, origin) {
        const [longitude, latitude] = geofence.geometryCenter.coordinates;
        const location = {
          id: geofence.externalId,
          name: geofence.description,
          metadata: geofence.metadata || {},
          latitude,
          longitude,
        };
        location.miles = straightLineMiles(origin, location);
        return location;
      }

      function renderResult(location) {
        const item = document.createElement('li');
        const button = document.createElement('button');
        button.type = 'button';

        const name = document.createElement('div');
        name.textContent = location.name;

        const distance = document.createElement('div');
        distance.className = 'distance';
        distance.textContent = `${location.miles.toFixed(1)} mi away (straight line)`;

        button.append(name, distance);

        ['hours', 'phone'].forEach((key) => {
          if (location.metadata[key]) {
            const detail = document.createElement('div');
            detail.className = 'detail';
            detail.textContent = String(location.metadata[key]);
            button.append(detail);
          }
        });

        item.append(button);
        resultsEl.append(item);
        return button;
      }

      async function selectLocation(origin, location, marker, button, fromMarker) {
        resultsEl.querySelectorAll('button').forEach((el) => el.removeAttribute('aria-current'));
        button.setAttribute('aria-current', 'true');
        button.scrollIntoView({ block: 'nearest' });

        // A marker click already opened its own popup. A list click has to open it.
        if (!fromMarker) {
          map.getMarkers().forEach((other) => {
            if (other !== marker && other.getPopup().isOpen()) {
              other.togglePopup();
            }
          });
          if (!marker.getPopup().isOpen()) {
            marker.togglePopup();
          }
        }

        map.flyTo({ center: [location.longitude, location.latitude], zoom: 15 });

        // Route distance and travel time for the selected location only.
        try {
          const { routes } = await Radar.distance({
            origin,
            destination: { latitude: location.latitude, longitude: location.longitude },
            modes: ['car'],
            units: 'imperial',
          });
          if (routes.car && routes.car.distance && routes.car.duration) {
            button.querySelector('.distance').textContent =
              `${routes.car.distance.text} by car, about ${routes.car.duration.text}`;
          }
        } catch (err) {
          // Keep the straight-line distance if the route request fails.
          console.error(err);
        }
      }

      async function searchNear(origin, label) {
        const thisSearch = ++searchCount;
        setStatus('Searching...');
        resultsEl.replaceChildren();
        map.clearMarkers();

        let geofences;
        try {
          ({ geofences } = await Radar.searchGeofences({
            near: origin,
            radius: RADIUS_METERS,
            tags: [TAG],
            limit: LIMIT,
            includeGeometry: false,
          }));
        } catch (err) {
          if (thisSearch !== searchCount) return;
          console.error(err);
          setStatus(err.status === 'ERROR_RATE_LIMIT'
            ? 'Too many searches. Wait a moment and try again.'
            : 'Search is unavailable right now. Try again.');
          return;
        }

        if (thisSearch !== searchCount) return; // a newer search has started

        if (geofences.length === 0) {
          setStatus(`No locations found near ${label}. Try another address.`);
          map.flyTo({ center: [origin.longitude, origin.latitude], zoom: 10 });
          return;
        }

        // One array drives both the list and the map, so they cannot disagree.
        const locations = geofences.map((geofence) => toLocation(geofence, origin));

        locations.forEach((location) => {
          const marker = Radar.ui.marker({ popup: { text: location.name } })
            .setLngLat([location.longitude, location.latitude])
            .addTo(map);
          const button = renderResult(location);

          button.addEventListener('click', () => selectLocation(origin, location, marker, button, false));
          marker.on('click', () => selectLocation(origin, location, marker, button, true));
        });

        map.fitToMarkers({ maxZoom: 14, padding: 60 });
        setStatus(`${locations.length} locations near ${label}, nearest first.`);
      }

      // Search by address. Works with no location permission.
      Radar.ui.autocomplete({
        container: 'autocomplete',
        width: '100%',
        placeholder: 'Address, city, or postal code',
        onSelection: (address) => {
          searchNear(
            { latitude: address.latitude, longitude: address.longitude },
            address.formattedAddress,
          );
        },
        onError: (err) => {
          console.error(err);
          setStatus('Address search is unavailable right now. Try again.');
        },
      });

      // Search by the visitor's position, only when they ask for it.
      document.getElementById('use-location').addEventListener('click', async () => {
        setStatus('Getting your location...');
        try {
          const { latitude, longitude } = await Radar.getLocation();
          searchNear({ latitude, longitude }, 'your location');
        } catch (err) {
          setStatus(err.status === 'ERROR_PERMISSIONS'
            ? 'Location permission is off. Search by address instead.'
            : 'Your location is unavailable. Search by address instead.');
        }
      });

      // Optional: start with results near an estimate of the visitor's area.
      Radar.ipGeocode()
        .then(({ address }) => {
          if (address && searchCount === 0) {
            searchNear(
              { latitude: address.latitude, longitude: address.longitude },
              address.city ? `${address.city} (estimated from your network)` : 'your approximate area',
            );
          }
        })
        .catch(() => {
          // No estimate available. The visitor can still search by address.
        });
    </script>
  </body>
</html>
```

```swift Swift theme={null}
import CoreLocation
import RadarSDK
import UIKit

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        Radar.initialize(publishableKey: "prj_test_pk_...")
        return true
    }
}

func findStores(near query: String) {
    // Search by address. Works with no location permission.
    Radar.geocode(address: query) { (status, addresses) in
        guard status == .success, let address = addresses?.first else {
            // Show that the address could not be found.
            return
        }

        let origin = CLLocation(latitude: address.coordinate.latitude, longitude: address.coordinate.longitude)

        Radar.searchGeofences(
            near: origin,
            radius: 10000,
            tags: ["store"],
            metadata: nil,
            limit: 10,
            includeGeometry: false
        ) { (status, _, geofences) in
            guard status == .success, let geofences = geofences else {
                // Show the error state.
                return
            }

            if geofences.isEmpty {
                // Show the empty state.
                return
            }

            // Geofences are sorted by distance from the origin. Render the list and the map from this one array.
            for geofence in geofences {
                guard let circle = geofence.geometry as? RadarCircleGeometry else { continue }
                let center = circle.center.coordinate
                let meters = origin.distance(from: CLLocation(latitude: center.latitude, longitude: center.longitude))
                print(geofence.externalId ?? "", geofence.__description, String(format: "%.1f mi away (straight line)", meters / 1609.344))
            }
        }
    }
}
```

```kotlin Kotlin theme={null}
import android.app.Application
import android.location.Location
import io.radar.sdk.Radar
import io.radar.sdk.model.RadarCircleGeometry

class MainApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        Radar.initialize(this, "prj_test_pk_...")
    }
}

fun findStores(query: String) {
    // Search by address. Works with no location permission.
    Radar.geocode(query) { geocodeStatus, addresses ->
        val address = addresses?.firstOrNull()
        if (geocodeStatus != Radar.RadarStatus.SUCCESS || address == null) {
            // Show that the address could not be found.
            return@geocode
        }

        val origin = Location("search").apply {
            latitude = address.coordinate.latitude
            longitude = address.coordinate.longitude
        }

        Radar.searchGeofences(
            near = origin,
            radius = 10000,
            tags = arrayOf("store"),
            metadata = null,
            limit = 10,
            includeGeometry = false
        ) { status, _, geofences ->
            if (status != Radar.RadarStatus.SUCCESS || geofences == null) {
                // Show the error state.
                return@searchGeofences
            }

            if (geofences.isEmpty()) {
                // Show the empty state.
                return@searchGeofences
            }

            // Geofences are sorted by distance from the origin. Render the list and the map from this one array.
            for (geofence in geofences) {
                val center = (geofence.geometry as? RadarCircleGeometry)?.center ?: continue
                val meters = FloatArray(1)
                Location.distanceBetween(origin.latitude, origin.longitude, center.latitude, center.longitude, meters)
                println("${geofence.externalId} ${geofence.description} ${"%.1f".format(meters[0] / 1609.344)} mi away (straight line)")
            }
        }
    }
}
```

```javascript React Native theme={null}
import Radar from 'react-native-radar';

Radar.initialize('prj_test_pk_...');

export async function findStores(query) {
  try {
    // Search by address. Works with no location permission.
    const { addresses } = await Radar.geocode({ address: query });
    if (!addresses || addresses.length === 0) {
      // Show that the address could not be found.
      return [];
    }

    const origin = { latitude: addresses[0].latitude, longitude: addresses[0].longitude };

    const { geofences } = await Radar.searchGeofences({
      near: origin,
      radius: 10000,
      tags: ['store'],
      limit: 10,
      includeGeometry: false,
    });

    if (!geofences || geofences.length === 0) {
      // Show the empty state.
      return [];
    }

    // Geofences are sorted by distance from the origin. Render the list and the map from this one array.
    return geofences.map((geofence) => {
      const [longitude, latitude] = geofence.geometryCenter.coordinates;
      return {
        id: geofence.externalId,
        name: geofence.description,
        metadata: geofence.metadata || {},
        latitude,
        longitude,
      };
    });
  } catch (err) {
    // Show the error state. The promise rejects with a Radar status such as ERROR_NETWORK in err.code.
    console.error(err.code);
    return [];
  }
}
```

## Prerequisites

* A publishable key. See [Choose the right API key](https://docs.radar.com/fundamentals/authentication-and-access.md#choose-the-right-api-key). Never put a secret key in client code.
* Your locations, each with a name, coordinates or an address, and an ID from your own system.
* **Web**: The examples use `radar-sdk-js` 5.3.0, `@radarlabs/plugin-maps` 1.2.0, and `@radarlabs/plugin-autocomplete` 1.2.0.
* No location permission. The "Use my location" button asks for it only when the visitor selects it.

## Load your locations

The locator searches geofences in your Radar project. Import your locations as geofences with the same `tag` (the example uses `store`), your own ID as the `externalId`, the display name as the `description`, and the fields you want to show as `metadata`. See [CSV import](https://docs.radar.com/geofencing/geofences-and-places.md#csv-import).

Geofence metadata is returned to anyone who can run a search with your publishable key. Put only public information in it.

## Accept an address

`Radar.ui.autocomplete()` renders a search input that suggests addresses, cities, and postal codes. When the visitor chooses a suggestion, `onSelection` receives an address with `latitude`, `longitude`, and `formattedAddress`, and the example uses those coordinates as the search origin.

This is the primary path, and it needs no location permission. For the component's options, see [Autocomplete, geocode, and validate addresses](https://docs.radar.com/maps/addresses.md#add-the-autocomplete-component).

## Accept the user's location

The "Use my location" button calls `Radar.getLocation()`, which triggers the browser's permission prompt. Call it from a button, not on page load, so the visitor understands why they are being asked. If the visitor denies permission, the example tells them to search by address and the rest of the page keeps working.

The last block of the example calls `Radar.ipGeocode()` to run a first search with no prompt. An IP-derived location is an estimate that can be wrong by a large distance, so label it as an estimate and let an address search replace it.

## Search nearby locations

`Radar.searchGeofences()` returns the geofences nearest to `near`, sorted by straight-line distance.

| Parameter | Value in the example | Notes |
| - | - | - |
| `near` | The search origin | If you omit it, the SDK requests the browser's location, which triggers a permission prompt. Always pass it. |
| `radius` | `10000` | Meters. The maximum is `10000`. |
| `tags` | `['store']` | Only geofences with one of these tags are returned. |
| `limit` | `10` | The number of results to show. |
| `includeGeometry` | `false` | The locator needs only each geofence's center, which is always returned as `geometryCenter`. |

Each geofence has `description`, `tag`, `externalId`, `metadata`, and `geometryCenter`, a GeoJSON point in `[longitude, latitude]` order. For every parameter and field, see [Search geofences](https://docs.radar.com/api/search.md#search-geofences).

## Show the list and the map

The example converts the response into one `locations` array and renders both the list and the markers from it in a single loop. That keeps the two views in sync: the same locations, in the same order, with each list button holding a reference to its marker. Before each search it clears the list and calls `map.clearMarkers()`, and afterward it calls `map.fitToMarkers()`.

Selecting a list entry and selecting a marker both call `selectLocation()`, so they lead to the same state: the entry is highlighted and scrolled into view, its popup is open, and the map moves to it.

List content is written with `textContent` and popups use the `text` option, so names and metadata are never interpreted as markup.

## Show route distance and travel time

Search results are ordered by straight-line distance, which ignores roads. Route distance and travel time follow roads and cost one extra request, so label each number for what it is.

When a location is selected, the example calls `Radar.distance()` and replaces the straight-line label with `routes.car.distance.text` and `routes.car.duration.text`. If the request fails or no drivable route exists, the straight-line label stays. To show travel time for every result at once, make one `Radar.matrix()` request after the search:

```javascript theme={null}
const { matrix } = await Radar.matrix({
  origins: [origin],
  destinations: locations.map(({ latitude, longitude }) => ({ latitude, longitude })),
  mode: 'car',
  units: 'imperial',
});

// matrix[0][i] is the route from the origin to locations[i].
matrix[0].forEach((route, index) => {
  locations[index].drive = route.duration ? route.duration.text : null;
});
```

See [Distance](https://docs.radar.com/api/routing.md#distance) and [Matrix](https://docs.radar.com/api/routing.md#matrix).

## Variations

A branch, ATM, or dealer finder is the same flow with different tags and metadata: import each type with its own tag, search several at once with `tags: ['branch', 'atm']`, and read each result's `tag` to choose a marker color or icon. If your locations already come from your own API, skip geofences: build the same `locations` array from your list, sort it by `straightLineMiles()` from the search origin, and render from it. To find public places, such as a chain or a category of business, use `Radar.searchPlaces()`. See [Search places](https://docs.radar.com/api/search.md#search-places).

## Native apps

The same flow works in a native app. The Radar iOS, Android, and React Native SDKs provide `Radar.searchGeofences`, `Radar.autocomplete`, `Radar.geocode`, and `Radar.getDistance`, and the native tabs in [Complete example](#complete-example) geocode a typed address and search near it. To render the map, see [Compatibility](https://docs.radar.com/maps/maps.md#compatibility). For setup, see [iOS SDK](https://docs.radar.com/sdk/ios.md), [Android SDK](https://docs.radar.com/sdk/android.md), and [React Native SDK](https://docs.radar.com/sdk/react-native.md).

## Handle results and errors

Every `Radar.*` method in the example returns a promise that rejects with a `RadarError`. Read its `status`.

| Result or error | What it means | What to do |
| - | - | - |
| An empty `geofences` array | No locations within `radius`. This is a successful response, not an error. | Show an empty state that names the searched place, and keep the search box usable. |
| `ERROR_PERMISSIONS` or `ERROR_LOCATION` from `Radar.getLocation()` | The visitor denied location permission, or the browser couldn't determine a position. | Tell the visitor to search by address. Don't block the page. |
| `ERROR_UNAUTHORIZED` | The key is wrong or revoked. | Show an unavailable state. Check the key and environment. |
| `ERROR_RATE_LIMIT` | Too many requests. | Ask the visitor to wait. Don't search on every keystroke or map move. |
| `ERROR_NETWORK` or another `RadarError` | The request failed. | Show a retry message. A new search retries. |
| `routes.car` missing, or the route request rejects | No route was found, or the request failed. | Keep the straight-line distance. |
| The map's `error` event fires before `load` | The map failed to load. | Keep the list working. See [Handle load failure](https://docs.radar.com/maps/maps.md#handle-load-failure). |
| A location is missing from results | It is disabled, has a different tag, is in the other environment, or is farther than `radius`. | Check the geofence in the dashboard for the environment that matches your key. |

## Test the integration

* **Passing case**: Block location for the page in your browser's site settings, type an address, and choose a suggestion. The same locations appear in the list and on the map, nearest first, and selecting one shows a driving distance and time.
* **Failing case**: Search for a city where you have no locations. The empty state names the place you searched, and the next search works.

For more, see [Test, troubleshoot, and go live](https://docs.radar.com/fundamentals/testing-and-launch.md).

## Production checklist

* [ ] The page uses the Live publishable key, and your locations are imported into the Live environment with the same tags.
* [ ] No secret key appears in client code, the page source, or a client-side environment variable.
* [ ] Geofence metadata contains only information you intend to be public.
* [ ] Address search is the default path, and location permission is requested only from a user action.
* [ ] Empty and error states exist for search, and the list works if the map fails.
* [ ] Straight-line and route distances are labeled, and the list and map use the same order.

## Build with an agent

Copy this prompt into a coding agent that has access to your repository.

```text theme={null}
Build a store locator in this repository with Radar.

Read https://docs.radar.com/maps/store-locators.md, https://docs.radar.com/sdk/web.md,
and https://docs.radar.com/api/search.md, and follow them for this platform.

Constraints:
- Use a publishable key read from configuration. Never put a secret key in client code.
- Address search must work with location permission denied.
- Render the list and the map from one array. Label straight-line and route distance.

Add tests for: an address search with location permission denied returns results; the
list and the map show the same locations in the same order; a search with no nearby
locations shows the empty state.
```

## See also

* [Search geofences](https://docs.radar.com/api/search.md#search-geofences) and [Search places](https://docs.radar.com/api/search.md#search-places)
* [Routing API](https://docs.radar.com/api/routing.md)
* [Web SDK](https://docs.radar.com/sdk/web.md)
* [Display maps](https://docs.radar.com/maps/maps.md)
* [Autocomplete, geocode, and validate addresses](https://docs.radar.com/maps/addresses.md)
* [Detect geofence events and place visits](https://docs.radar.com/geofencing/geofences-and-places.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.