It is not necessary to add a layer to a map in order to execute a spatial query. However, this sample includes a map because it provides a convenient way to ask users for their HTML5 location. To learn more, go to L.esri.
in the API reference.
<html>
<head>
<meta charset="utf-8" />
<title>Query without a map</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.10/dist/esri-leaflet.js"></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>
<style>
#message {
margin: 10px;
}
</style>
<div id="map">
<div id="message">computing...</div>
</div>
<div id="invisibleMap"></div>
<script>
if (window.location.host === "esri.github.io" && window.location.protocol !== "https:") {
window.location.protocol = "https";
} // html5 geolocation requires a secure connectio
document.getElementById("map").style.height = "100px";
const message = document.getElementById("message");
const map = L.map("invisibleMap");
map.locate();
map.on("locationfound", function (e) {
// use location to find out which census block they are inside
L.esri
.query({
url: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer/1"
})
.intersects(e.latlng)
.run(function (error, censusBlocks) {
if (error) {
message.innerHTML = "there may have been an error querying your location";
return;
}
if (censusBlocks.features.length > 0) {
// if we find a match dig into the feature attributes to retrive median age
message.innerHTML =
"the median age of the census block where you are currently located is <b>" +
censusBlocks.features[0].properties.MED_AGE +
"</b> years old";
} else {
// otherwise, fail gracefully
message.innerHTML = "either you aren't currently in the United States or you prefer not to say";
}
});
});
</script>
</body>
</html>