Locate and select feature by id

In this example, we will locate and select a feature on the map, for a given feature id.

In the example dataset, we will use the layer "Places", id=6, and locate feature with id=33.

We expect to find this feature, select it, then recenter the map around it.

Example

Try it out in Codepen.io

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <meta charset="UTF-8">
    <style>
      #my-custom-map {
        width: 600px;
        height: 600px;
        border: 1px solid grey;
        margin-top: 1rem;
      }
    </style>
  </head>
  <body class="jmap_wrapper">
    <button
      id="selectFeature"
      onclick="alert('The map is loading, try again when the map is displayed on screen')">
      Find, select, and display feature
    </button>
    <button
      id="unSelectFeature"
      onclick="alert('The map is loading, try again when the map is displayed on screen')">
      Unselect feature
    </button>
    <div id="my-custom-map"></div>
    <script type="text/javascript">
      const PLACE_LAYER_ID = 6;
      const FEATURE_ID = 33;
      let isLoading = false;
      window.selectFeature = () => {
        if (isLoading) {
          return alert("Locating the feature, please wait");
        }
        isLoading = true;
        if (!JMap.Layer.isSelectableById(PLACE_LAYER_ID)) {
          JMap.Layer.setSelectabilityById(PLACE_LAYER_ID, true);
        }
        JMap.Feature
          .getById(PLACE_LAYER_ID, FEATURE_ID)
          .then(feature => {
            isLoading = false;
            JMap.Map.Selection.setLayerSelection(PLACE_LAYER_ID, feature);
            JMap.Map.fitFeatures([feature]);
          })
          .catch(error => {
            isLoading = false;
            console.error("An error occured", error);
            alert("Cannot get the feature !");
          });
      };
      window.unSelectFeature = () => {
        JMap.Map.Selection.clearLayersSelection([PLACE_LAYER_ID]);
      };
      window.JMAP_OPTIONS = {
        projectId: 1,
        restBaseUrl: "https://jmapdoc.jmaponline.net/services/rest/v2.0",
        anonymous: true,
        map: {
          containerId: "my-custom-map",
          zoom: 13.797865986918877,
          center: {
            x: -73.48063889179525,
            y: 45.664231577062765
          }
        },
        onReady: () => {
          JMap.Event.Map.on.mapLoad("my-listener", () => {
            document.getElementById("selectFeature").onclick = window.selectFeature;
            document.getElementById("unSelectFeature").onclick = window.unSelectFeature;
          });
        }
      };
    </script>
    <script defer type="text/javascript" src="https://cdn.jsdelivr.net/npm/jmap-core-js@7_Kathmandu_HF3"></script>  
  </body>
</html>

Dernière mise à jour

K2 Geospatial 2023