> For the complete documentation index, see [llms.txt](https://docs.mapbox.com/help/ja/llms.txt)

# Local search with Mapbox Search JS

In this tutorial, you will use [**Mapbox Search JS**](https://docs.mapbox.com/mapbox-search-js/guides/) and its optional `proximity` and `bbox` parameters and create a local search app for UC Berkeley that limits results to the Berkeley area and biases results around the campus itself.

[**Mapbox Search JS**](https://docs.mapbox.com/mapbox-search-js/guides/) is a JS client side library that provides interactive search experiences like [Address Autofill](https://docs.mapbox.com/mapbox-search-js/guides/autofill/), [Search Box](https://docs.mapbox.com/mapbox-search-js/guides/search/) and [Geocoding](https://docs.mapbox.com/mapbox-search-js/guides/geocoding/). This tutorial will use the library's [Search Box](https://docs.mapbox.com/mapbox-search-js/guides/search/) to add interactive search to the application.

### What we'll cover

-   Creating a map with [**Mapbox GL JS**](https://docs.mapbox.com/mapbox-gl-js/)
-   Adding an interactive search box using [**Mapbox Search JS**](https://docs.mapbox.com/mapbox-search-js/guides/)
-   Using optional parameters `proximity` and `bbox` and how these affect results.

## Prerequisites

To complete this tutorial, you will need:

-   **A Mapbox account and access token.** [Sign up](https://account.mapbox.com/auth/signup) for a free account. Your access tokens are on your [Account page](https://www.mapbox.com/account).
-   **Mapbox GL JS.** Mapbox GL JS is a JavaScript API for building web maps.
-   **An IDE / Code editor.** Use a program like [VSCode](https://code.visualstudio.com/) or [Sublime Text](https://www.sublimetext.com/) for writing HTML, CSS, and JavaScript.
-   **Familiarity with front-end development**: Beginner experience with HTML, CSS and JavaScript.

## Create your app

To create a local search app, you will need to start by creating an HTML file and initializing the map. Then you will add **Mapbox Search JS** and learn how to customize the search responses using optional parameters of the underlying Search Box API.

### Set up your HTML file

Open your text editor and create a new file named `index.html`. Set up this new HTML file by pasting the following code into your text editor. This code creates the structure of the page.

**Mapbox GL JS** JavaScript and CSS is imported in the top of the file. There are basic CSS styles declared to create a full screen map, and there is a `<div>` element with the ID `map` which is the container to which the map will be attached.

```html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Local search app</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <script src="https://api.mapbox.com/mapbox-gl-js/v3.25.0/mapbox-gl.js"></script>
    <link
      href="https://api.mapbox.com/mapbox-gl-js/v3.25.0/mapbox-gl.css"
      rel="stylesheet"
    />
    <style>
      body {
        margin: 0;
        padding: 0;
      }

      #map {
        position: absolute;
        top: 0;
        bottom: 0;
        width: 100%;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
  </body>
</html>
```

### Initialize the map

Next, you will add the **Mapbox GL JS** code that initializes a map, which will be displayed in the `#map` div you created in the last step. In `index.html`, place the following snippet above the closing `</body>` tag. Make sure that you set the `YOUR_MAPBOX_ACCESS_TOKEN` constant equal to your Mapbox access token available in [your account](https://console.mapbox.com/).

```html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Local search app</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <script src="https://api.mapbox.com/mapbox-gl-js/CONSTANTS::VERSION_MAPBOXGLJS/mapbox-gl.js"></script>
    <link
      href="https://api.mapbox.com/mapbox-gl-js/CONSTANTS::VERSION_MAPBOXGLJS/mapbox-gl.css"
      rel="stylesheet"
    />
    <style>
      body {
        margin: 0;
        padding: 0;
      }

      #map {
        position: absolute;
        top: 0;
        bottom: 0;
        width: 100%;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>
      const map = new mapboxgl.Map({
        accessToken: 'YOUR_MAPBOX_ACCESS_TOKEN',
        container: 'map', // Container ID
        style: 'mapbox://styles/mapbox/standard', // Map style to use
        center: [-122.25948, 37.87221], // Starting position [lng, lat]
        zoom: 12 // Starting zoom level
      });
    </script>
  </body>
</html>
```

The code snippet above declares a `new mapboxgl.Map` instance. It connects the `Map` to the `#map` div, sets the map style, map center (coordinates of UC Berkeley) and zoom level.

Save your changes. Open the HTML file in your browser to see the rendered map.

![Screenshot showing a rendered Mapbox map](https://docs.mapbox.com/help/ja/assets/ideal-img/tutorials--local-search-search-box--initial-map.23921f0.480.png)

### Add a marker to the map

The next step is to add a marker to the map at the campus's coordinates to show the landmark's location.

After the map initialization code that you wrote in the last step, add a [Marker](https://docs.mapbox.com/mapbox-gl-js/api/markers/#marker) to the map with the highlighted snippet below.

```html
...

<body>
    <div id="map"></div>
    <script>
      const map = new mapboxgl.Map({
        accessToken: 'YOUR_MAPBOX_ACCESS_TOKEN',
        container: 'map', // Container ID
        style: 'mapbox://styles/mapbox/standard',
        center: [-122.25948, 37.87221], // Starting position [lng, lat]
        zoom: 12 // Starting zoom level
      });
      // highlight-start
      const marker = new mapboxgl.Marker() // initialize a new marker
        .setLngLat([-122.25948, 37.87221]) // Marker [lng, lat] coordinates
        .addTo(map); // Add the marker to the map
      // highlight-end
    </script>
  </body>
  ...
```

Save your changes and refresh the page in your browser. There will be a marker on the map at the specified coordinates, which are the coordinates of the UC Berkeley campus.

## Add Mapbox Search JS

The next step is to add **Mapbox Search JS**. To do this, first you need to add links to the Search JS script to the head of `index.html`. Then you are going to store your access token in a variable (`ACCESS_TOKEN`) and pass that to both **Mapbox GL JS** and **Mapbox Search JS**. Next, you'll add a `window` on load event listener to make sure the page is fully loaded before instantiating Search JS.

Review the code snippet below and add the highlighted changes to your `index.html` file.

```html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Local search app - Mapbox Tutorials</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <script src="https://api.mapbox.com/mapbox-gl-js/v3.25.0/mapbox-gl.js"></script>
    // highlight-start
    <script id="search-js" defer src="https://api.mapbox.com/search-js/v1.2.0/web.js"></script>
    // highlight-end
    <link
      href="https://api.mapbox.com/mapbox-gl-js/v3.25.0/mapbox-gl.css"
      rel="stylesheet"
    />
    <style>
      body {
        margin: 0;
        padding: 0;
      }

      #map {
        position: absolute;
        top: 0;
        bottom: 0;
        width: 100%;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>
      // highlight-start
        const ACCESS_TOKEN = 'YOUR_MAPBOX_ACCESS_TOKEN';
     
      // highlight-end
        const map = new mapboxgl.Map({
            accessToken: ACCESS_TOKEN,
            container: 'map',
            style: 'mapbox://styles/mapbox/standard',
            center: [-122.25948, 37.87221], 
            zoom: 12 
        });
       
        const marker = new mapboxgl.Marker() 
            .setLngLat([-122.25948, 37.87221]) 
            .addTo(map);

      // highlight-start
        window.addEventListener('load', () => {
            const searchBox = new MapboxSearchBox(); // creates a new SearchBox instance
            searchBox.accessToken = ACCESS_TOKEN; // provides your accessToken to Searchbox for requests
            searchBox.marker = true; // Adds a marker to the map after clicking a search result
            searchBox.mapboxgl = mapboxgl; // connects
            searchBox.componentOptions = { allowReverse: true, flipCoordinates: true };
            map.addControl(searchBox); // Adds searchBox to the Mapbox GL JS control area (top right)
        });
        // highlight-end

    </script>
  </body>
</html>
```

Make these changes, save the file and refresh the page in your browser. You will see a search box in the upper right corner of the map. You can type a search term into the box and select a result, and the map will fly to that location.

Your browser doesn't support HTML5 video. Open [link to the video](https://docs.mapbox.com/help/ja/help/ja/assets/medias/tutorials--local-search-with-search-box--search-box-added-0ec88b37a681816eeb4d9f75f236f186.mp4).

## Customizing Search Results

Now that you have the search box added to the map, you can use the Search Box optional parameters to bias results around the UC Berkeley campus and limit results to the Berkeley area.

### Optional Parameters of Mapbox Search JS

Under the hood the Search Box added in the previous step, uses the [Search Box API](https://docs.mapbox.com/api/search/search-box/). This API has optional parameters allow you to customize your query so that you receive the results that are the most relevant to you. For the full list of the optional parameters, see the [Search Box API documentation](https://docs.mapbox.com/api/search/search-box/#get-suggested-results).

This tutorial will use two optional parameters that are especially useful for biasing results to a specific geographic location: `proximity` and `bbox`.

#### The `proximity` parameter

The `proximity` parameter allows you to bias the response in favor of results that are closer to a specified location. This makes sure that the query results that are closer to this location are prioritized over ones that are further away. The parameter has 2 potential values:

-   the string `ip` which biases the results around a reverse IP lookup (a location near you).
-   two comma-separated coordinates in `longitude,latitude` order

To find the coordinates of a location, you can use the Mapbox [Location Helper](https://labs.mapbox.com/location-helper) tool.

Since the `proximity` parameter is not exclusive, it does not restrict results to an area, but relevant results that are close to the provided coordinates are returned before relevant results that are further away.

#### The `bbox` parameter

The `bbox` parameter allows you to limit results to only those contained within a supplied bounding box. Bounding boxes need to be formatted as four coordinates separated by commas, in `minLon,minLat,maxLon,maxLat` order.

You can use any coordinates for a bounding box, as long as they describe a box shape. To find the coordinates for a bounding box, use the [Location Helper](https://labs.mapbox.com/location-helper/) tool.

### Add the `bbox` and `proximity` parameters

In your `addEventListener` add a `searchBox.options` object with `bbox` and `proximity` parameters to the Search Box JS code you added in the last step. The `bbox` parameter will limit results to the Berkeley area, and the `proximity` parameter will bias results around the UC Berkeley campus. You will also set the `placeholder` text for the search box to 'Search for places in Berkeley'.

```js
  ...
      window.addEventListener('load', () => {
        const searchBox = new MapboxSearchBox();
        searchBox.accessToken = ACCESS_TOKEN;
        // highlight-start
        searchBox.options = {
          proximity: [-122.25948, 37.87221], // Coordinates of UC Berkeley campus
          bbox: [
            [-122.30331, 37.85247], // bounding box southwest corner
            [-122.24538, 37.88487] // bounding box northeast corner
          ]
        };
        searchBox.placeholder = 'Search for places in Berkeley';
        // highlight-end
        searchBox.marker = true;
        searchBox.mapboxgl = mapboxgl;
        searchBox.componentOptions = {
          allowReverse: true,
          flipCoordinates: true
        };
        map.addControl(searchBox); // Adds the search box control to the map
      });
  ...
```

Save the HTML file and refresh the page in your browser. Now, when you enter a search into the search box, you will not receive any results outside of the bounding box. And the results that the Search Box returns are weighted according to their proximity to the Berkeley campus.

> **Note: Visualizing the bounding box**
> 
> If you want to visualize the bounding box on the map, you can use an `addSource()` and `addLayer()` function to add a geojson polygon source (which is based on the coordinates of the bounding box) and a fill layer to the map. This will allow you to see the area that is being limited by the `bbox` parameter. This can be helpful when troubleshooting search results.
> 
> ![Screenshot showing a bounding box polygon on a map](https://docs.mapbox.com/help/ja/assets/ideal-img/tutorials--local-search-search-box--bbox-polygon.6ba1039.480.png)Details
> 
> **Optional Code to visualize `bbox`**
> 
> Use this code to visualize the bounding box on the map. Add it after the map initialization.
> 
> ```js
> map.on('load', () => {
>     map.addSource('bbox', {
>       "type": "geojson",
>       "data": {
>           "type": "Feature",
>           "properties": {},
>           "geometry": {
>               "coordinates": [
>               [
>                   [-122.24560, 37.88466],
>                   [-122.24539, 37.85240],
>                   [-122.30337, 37.85251],
>                   [-122.30332, 37.88483],
>                   [-122.24560, 37.88466] // closing the polygon
>               ]
>               ],
>               "type": "Polygon"
>           }
>       }
>   });
> 
>   map.addLayer({
>       "id": "bbox",
>       "type": "fill",
>       "source": "bbox",
>       "layout": {},
>       "paint": {
>           "fill-color": "#088",
>           "fill-opacity": 0.2
>       }
>   });
> })
> ```

## Finished product

**Congratulations!** 🎉 You have completed a local search app that when a user enters a query into the search box, biases the results around a geographic point and excludes any results that are located outside a bounded area.

### Full Demo Code

```html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Local search app - Mapbox Tutorials</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <script src="https://api.mapbox.com/mapbox-gl-js/v3.25.0/mapbox-gl.js"></script>
    <script id="search-js" defer="" src="https://api.mapbox.com/search-js/v1.2.0/web.js"></script>
    <link
      href="https://api.mapbox.com/mapbox-gl-js/v3.25.0/mapbox-gl.css"
      rel="stylesheet"
    />
    <style>
      body {
        margin: 0;
        padding: 0;
      }

      #map {
        position: absolute;
        top: 0;
        bottom: 0;
        width: 100%;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>
        const ACCESS_TOKEN = 'YOUR_MAPBOX_ACCESS_TOKEN';
        
        const map = new mapboxgl.Map({
            accessToken: ACCESS_TOKEN,
            container: 'map', // Container ID
            style: 'mapbox://styles/mapbox/standard',
            center: [-122.25948, 37.87221], // Starting position [lng, lat]
            zoom: 12 // Starting zoom level
        });
       
        const marker = new mapboxgl.Marker() // initialize a new marker
          .setLngLat([-122.25948, 37.87221]) // Marker [lng, lat] coordinates
          .addTo(map); // Add the marker to the map

        window.addEventListener('load', () => {
          const searchBox = new MapboxSearchBox();
          searchBox.accessToken = ACCESS_TOKEN;
          searchBox.options = {
            proximity: [-122.25948, 37.87221], // Coordinates of UC Berkeley campus
            bbox: [
              [-122.30331, 37.85247], // bounding box southwest corner
              [-122.24538, 37.88487] // bounding box northeast corner
            ]
          };
          searchBox.placeholder = 'Search for places in Berkeley';
          searchBox.marker = true;
          searchBox.mapboxgl = mapboxgl;
          searchBox.componentOptions = {
            allowReverse: true,
            flipCoordinates: true
          };
          map.addControl(searchBox); // Adds the search box control to the map
        });

    </script>
  </body>
</html>
```

## Next steps

You have learned how to use Mapbox Search JS and the Search Box API's optional parameters to bias results around a location and limit results to a specific area. You have also seen how to use the to integrate interactive search into a web app.

### What we covered

-   Creating a map with [Mapbox GL JS](https://docs.mapbox.com/mapbox-gl-js/)
-   Adding interactive search using [Mapbox Search JS](https://docs.mapbox.com/mapbox-search-js/guides/)
-   Understanding & using the optional parameters `proximity` and `bbox`.

### Learn more

There are a lot of things you could do to build this app out more. You could:

-   Add a visualization toggle for the bounding box on the map using a polygon layer via the code snippet in the "Add the `bbox` and `proximity` parameters" section in [Step 5](https://docs.mapbox.com/help/ja/tutorials/local-search-search-box-api/?step=4).
-   Use Turf.js to analyze the distances of the various results from the UC Berkeley campus. (See the [Sort stores by distance](https://docs.mapbox.com/help/ja/tutorials/geocode-and-sort-stores/) tutorial.)
-   Add custom CSS styles to the search box to customize its appearance, by adding the [`theme`](https://docs.mapbox.com/mapbox-search-js/api/web/search/#mapboxsearchbox#theme) property to `searchBox`. View a custom theme example in the [Search JS docs](https://docs.mapbox.com/mapbox-search-js/example/theming/)

> **Related content (related): [Add POI Search to a Map in aReact App](https://docs.mapbox.com/help/ja/tutorials/poi-search-react/)**
> 
> Learn how to add a search box to a map in a Reach app to quickly search for points of interest (POIs) using the Search Box API.