Link Search Menu Expand Document

Locate and select feature(s) by location

In this example, we will locate and select a feature on the map for a given location and on any selectable layer.

The default coordinates will select a feature on layer “Places”, id=6.

Example

Show example in Codepen.io

Latitude:  Longitude: 

You can also click on the map to choose a location: 


The code:

<!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">
  <span>Latitude:&nbsp;</span>
  <input placeholder="Enter latitude" id="latitude" value="-73.49440489999999" />
  <span>Longitude:&nbsp;</span>
  <input placeholder="Enter longitude" id="longitude" value="45.667717299999985" />
  <button id="selectFeature" onclick="alert('The map is loading, try again when the map is displayed on screen')">Select</button>
  <button id="unSelectFeature" onclick="alert('The map is loading, try again when the map is displayed on screen')">
    <span>Unselect</span>
  </button>
  <br />
  <br />
  <span>You can also click on the map to choose a location:&nbsp;</span>
  <div id="my-custom-map">
  </div>
  <script type="text/javascript">
    window.selectFeature = () => {
      const latitude = Number(document.getElementById("latitude").value);
      const longitude = Number(document.getElementById("longitude").value);
      if (!latitude || isNaN(latitude)) {
        return alert("Please enter a valid latitude");
      }
      if (!longitude || isNaN(latitude)) {
        return alert("Please enter a valid longitude");
      }
      JMap.Map.Selection.selectOnAllLayersAtLocation({
        x: latitude,
        y: longitude
      });
    };
    window.unSelectFeature = () => {
      JMap.Map.Selection.clearSelection();
    };
    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.49440489999999,
          y: 45.667717299999985
        },
      },
      onReady: () => {
        JMap.Event.Map.on.mapLoad("my-listener", () => {
          document.getElementById("selectFeature").onclick = window.selectFeature;
          document.getElementById("unSelectFeature").onclick = window.unSelectFeature;
        });
        JMap.Event.Map.on.click("selectLocation", (res) => {
          document.getElementById("latitude").value = res.location.x;
          document.getElementById("longitude").value = res.location.y;
        });
      }
    };
  </script>
  <script defer type="text/javascript" src="https://cdn.jsdelivr.net/npm/jmap-core-js@jmap-ng-doc"></script>
</body>
</html>

Copyright © 2022 K2 Geospatial.