Select to view content in your preferred language

Acessing attribute from web Map in Experince builder

28
0
a week ago
SajithRanatunga
New Contributor

Hi,

 

How we can access the attribute from data leyer in a Web Map? For exmaple, I have a web map with weather stations. I need to develop a custom widget on Experince Builder, when I click on station, widget should take stationID from attribute and then run on API to take real time data? 

I tried to get the StationID, but nothing worked so far. 

 

Any idea how we can read attribute and make it work. 

here is the code 

import { React, AllWidgetProps } from "jimu-core";
import { JimuMapView, JimuMapViewComponent } from "jimu-arcgis";
import { useState } from "react";

export default function RealTimeStationWidget(props: AllWidgetProps<any>) {
  const [stationData, setStationData] = useState<any>(null);
  const [mapView, setMapView] = useState<JimuMapView | null>(null);

  const onActiveViewChange = (jmv: JimuMapView) => {
    console.log(" Active view set", jmv.view);
    setMapView(jmv);

    jmv.view.on("click", async (event: any) => {
      console.log("🟡 Map clicked");

      const hit = await jmv.view.hitTest(event);
      console.log("🔍 Hit test result:", hit.results);

      for (let i = 0; i < hit.results.length; i++) {
        const attr = hit.results[i].graphic?.attributes;
        console.log(`🎯 Graphic ${i} full attributes:`, attr);
        console.log(
          `🎯 Attribute keys:`,
          attr ? Object.keys(attr) : "No attributes"
        );

        if (attr && attr.stasjonID) {
          console.log(" Found stasjonID:", attr.stasjonID);
          const stationId = attr.stasjonID;
          const data = await fetchStationData(stationId);
          setStationData(data);
          return;
        }
      }

      // :warning: Place this outside the for-loop to log only once if none matched
      console.warn(":warning: No stasjonID found in clicked graphics.");
    });
  };

  const fetchStationData = async (stationId: string) => {
    const apiKey = "xyzxyzx";
    const url = "https://url";

    let waterLevel = "N/A";
    let waterFlow = "N/A";
    let waterTemp = "N/A";
    let timestamp = "N/A";

    try {
      const res1 = await fetch(
        `${url}?StationId=${stationId}&Parameter=`,
        {
          headers: { accept: "application/json", "API-Key": apiKey },
        }
      );
      const json1 = await res1.json();
      if (json1.data?.[0]?.observations?.[0]) {
        waterLevel = json1.data[0].observations[0].value;
        timestamp = json1.data[0].observations[0].time;
      }
    } catch (e) {
      console.error("Water level error:", e);
    }

    try {
      const res2 = await fetch(
        `${url}?StationId=${stationId}&Parameter=`,
        {
          headers: { accept: "application/json", "API-Key": apiKey },
        }
      );
      const json2 = await res2.json();
      if (json2.data?.[0]?.observations?.[0]) {
        waterFlow = json2.data[0].observations[0].value;
        if (timestamp === "N/A") timestamp = json2.data[0].observations[0].time;
      }
    } catch (e) {
      console.error("Water flow error:", e);
    }

    try {
      const res3 = await fetch(
        `${url}?StationId=${stationId}&Parameter=`,
        {
          headers: { accept: "application/json", "API-Key": apiKey },
        }
      );
      const json3 = await res3.json();
      if (json3.data?.[0]?.observations?.[0]) {
        waterTemp = json3.data[0].observations[0].value;
        if (timestamp === "N/A") timestamp = json3.data[0].observations[0].time;
      }
    } catch (e) {
      console.error("Water temp error:", e);
    }

    return { stationId, waterLevel, waterFlow, waterTemp, timestamp };
  };

  return (
    <div style={{ padding: "1rem" }}>
      <JimuMapViewComponent
        useMapWidgetId={props.useMapWidgetIds?.[0]}
        onActiveViewChange={onActiveViewChange}
      />
      <h3>Real-Time Station Data</h3>
      {stationData ? (
        <div>
          <p>
            <strong>Station ID:</strong> {stationData.stationId}
          </p>
          <p>
            <strong>Water Level:</strong> {stationData.waterLevel} m
          </p>
          <p>
            <strong>Flow:</strong> {stationData.waterFlow} m³/s
          </p>
          <p>
            <strong>Temperature:</strong> {stationData.waterTemp} °C
          </p>
          <p>
            <strong>Time:</strong> {stationData.timestamp}
          </p>
        </div>
      ) : (
        <p>Click a station to view real-time data</p>
      )}
    </div>
  );
}
0 Kudos
0 Replies