Zoom to a subset of features

Create a latLngBounds object from the client that contains geometries fetched from a feature service. This is necessary when working with older feature services (prior to ArcGIS Server 10.3.1), which do not support making direct requests to the server for the 'bounds' of features matching a query.

Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<html>
  <head>
    <meta charset="utf-8" />
    <title>Zoom to to a subset of features</title>
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no" />
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" crossorigin="" />
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" crossorigin=""></script>

    <!-- Load Esri Leaflet from CDN -->
    <script src="https://unpkg.com/esri-leaflet@3.0.12/dist/esri-leaflet.js"></script>

    <!-- Load Esri Leaflet Vector from CDN -->
    <script src="https://unpkg.com/esri-leaflet-vector@4.2.5/dist/esri-leaflet-vector.js" crossorigin=""></script>
    <style>
      html,
      body,
      #map {
        padding: 0;
        margin: 0;
        height: 100%;
        width: 100%;
        font-family: Arial, Helvetica, sans-serif;
        font-size: 14px;
        color: #323232;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>
      const accessToken = "YOUR_ACCESS_TOKEN";

      const map = L.map("map").setView([40, -100], 5);

      L.esri.Vector.vectorBasemapLayer("arcgis/dark-gray/base", {
        token: accessToken
      }).addTo(map);

      // add a graphic layer composed of selected US Counties
      const fl = L.esri
        .featureLayer({
          url: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer/2",
          where: "NAME='Los Angeles' OR NAME='San Bernardino'"
        })
        .addTo(map);

      // listen for when all features have been retrieved from the server
      fl.once("load", function (evt) {
        // create a new empty Leaflet bounds object
        const bounds = L.latLngBounds([]);
        // loop through the features returned by the server
        fl.eachFeature(function (layer) {
          // get the bounds of an individual feature
          const layerBounds = layer.getBounds();
          // extend the bounds of the collection to fit the bounds of the new feature
          bounds.extend(layerBounds);
        });

        // once we've looped through all the features, zoom the map to the extent of the collection
        map.fitBounds(bounds);
      });
    </script>
  </body>
</html>

Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.