How to limit search results to an extent with Esri Javascript map?

724 Views Asked by At

I believe by default the 4.13 Esri Javascript map will search addresses by the current map view extent. The issue is that if the user zooms in or out too far, the search results return addresses VERY far away. Here is my code:

function initESRIMap() {
require(["esri/Map", "esri/views/MapView", "esri/widgets/Search", "esri/layers/FeatureLayer", "esri/widgets/Popup", "esri/geometry/Extent", "esri/geometry/Geometry"], function (
  Map,
  MapView,
  Search,
  FeatureLayer,
  Popup,
  Extent,
  Geometry
) {      
  var esriMap = new Map({
    basemap: "streets",
  });

  var esriView = new MapView({
    container: "map-div",
    map: esriMap,
    center: LatLong,
    zoom: 11,
  });
  var search = new Search({
    view: esriView,
  });}

I want to be able to get the same search results REGARDLESS of my map view location. BUT limit results to a specific area. Therefore if I'm viewing another country I'll still see search results from my extent.

1

There are 1 best solutions below

0
On

A search widget can be customized to use custom sources, and a custom source can be customized to use a filter, which can include a map extent.

For example, let's define a custom SearchSource - we'll just use the same search endpoint as the standard ArcGIS World Geocoder service, but we'll add a filter:

const source = {
  locator: new Locator({
    url: "https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer"
  }),
  filter: {
    geometry: new Extent({
      xmax: -12921954.804910611,
      xmin: -13126806.04071496,
      ymax: 3909898.0736186495,
      ymin: 3801204.619397087,
      spatialReference: {
        wkid: 102100
      }
    })
  },
  maxSuggestions: 10
};

Now when we're defining our search widget, we'll include this in the source property array, and we'll turn off includeDefaultSources so that the original, unbounded source, is not used:

const search = new Search({
  view,
  includeDefaultSources: false,
  sources: [source]
});

Working Codesandbox

In this example, I set the extent in the filter to be around the area of san diego / tijuana. Wherever you pan or zoom on the map, you'll still only get results from that area. For example, move the map over to seattle, or china, or whatever, and search for something generic ("park", "road", whatever), and you'll see that no matter what the map's extent is, the search results will be limited to what you put in the search source's filter.

Note this answer was written with 4.18.