I've been tasked with finding a way to call a web api to pull a json response. The use would enter an address and an https post request would be made. The results would be displayed and inserted into a feature layer.
Does anyone know of an example widget that makes this type of request?
Thank you.
Hi Davin, I am just starting to research this as well. Did you make any progress?
I dont know about a post request, but it would probably look similar to something like this get request. In this example, when the input is changed, a fetch request is made to the what3words api and the results (the coordinates) are used to create an esri Point and its stored in state. Then the state (point coordinates) is displayed on the widget. Instead of displaying the results, you could use the esri js api to create geometry and add it to an existing layer or as a graphic to the map.
Hope this helps!
import { React, jsx } from "jimu-core";
import { useState } from "react";
import Point from "@arcgis/core/geometry/Point";
export default function Widget(props) {
const [point, setPoint] = useState(null);
const [error, setError] = useState(null);
function debounce(func, delay) {
let timeoutId;
return function (...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
const debouncedFetch = debounce((inputValue) => {
// Your fetch logic here
fetch(
"https://api.what3words.com/v3/convert-to-coordinates?words=filled.count.soap&key=YOUR_API_KEY"
)
.then((res) => res.json())
.then((data) => {
if (!data.coordinates) {
setError("No coordinates found.");
} else {
setPoint(
new Point({
longitude: data.coordinates.lng,
latitude: data.coordinates.lat,
})
);
}
})
.catch((err) => setError("Something went wrong."));
}, 300); // 300 milliseconds delay
return (
<div className="bg-dark p-5">
<p className="text-light">Fetching Widget</p>
<input
type="text"
placeholder="Enter 3 words"
onChange={debouncedFetch}
></input>
<p className="text-light">
{point?.latitude}, {point?.longitude}
</p>
<p className="text-light">{error}</p>
</div>
);
}
Here is a working example of what I was saying. To use it you will need a free api key from What3Words.
Thanks so much for posting this example.