Query Result to a Global Variable?

688
1
11-11-2019 04:18 PM
victhomas
New Contributor III

Hello,

I'm trying to get the result from a query and pass it out to a global variable and do something with it outside of the require().  Is it possible to do so?  The current code that I put together from various sources does not work, please any help or advice would be tremendous.  Thanks.

<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no">
  <title>ArcGIS JavaScript Tutorials: Create a Starter App</title>
  <style>
    html, body, #viewDiv {
      padding: 0;
      margin: 0;
      height: 90%;
      width: 100%;
    }
  </style>
  
  <link rel="stylesheet" href="https://js.arcgis.com/4.13/esri/css/main.css">
  <script src="https://js.arcgis.com/4.13/"></script>
  
  <script>  
	var fAttribute; //global variable
    require([
		"esri/Map",
		"esri/views/MapView",
		"esri/layers/FeatureLayer",
		"esri/layers/GraphicsLayer",
		"esri/Graphic"
    ], function(Map, MapView, FeatureLayer, GraphicsLayer, Graphic) 
	{

		var map = new Map({
			basemap: "topo-vector"
		});
	  
		var featureLayer = new FeatureLayer({
			url: "https://services3.arcgis.com/GVgbJbqm8hXASVYi/arcgis/rest/services/Trailheads_Styled/FeatureServer/0",
		});

		var graphicsLayer = new GraphicsLayer();
		map.add(featureLayer); 
		var view = new MapView({
			container: "viewDiv",
			map: map,
			center: [-118.80500,34.02700],
			zoom: 13
		});
		
		function QueryParkName(featureLayer)
		{
			var query = featureLayer.createQuery();
			query.where = "TRL_NAME = 'Glade Trail - Topanga'";
			query.outFields = ["*"];
			featureLayer.queryFeatures(query).then(function(response)
			{
				fAttribute = response.features[0].attributes.PARK_NAME; 
				console.log("Result: "+fAttribute); //display correctly
				
			});
			
		}
		QueryParkName(featureLayer);
                console.log("Result Outside of QueryParkName: "+fAttribute); //display undefined	
	})
	
	function DisplayName()
	{
		console.log("Park Name: "+fAttribute); //display undefined. 
	}
	DisplayName();
	
  </script>
</head>
<body>
  <div id="viewDiv"></div>
</body>
</html>‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍
0 Kudos
1 Reply
KenBuja
MVP Esteemed Contributor

It's not a problem of accessing the variable outside the require, but rather of timing. If you add a button to the body to run the function DisplayName, clicking the button will show the queried park name.

<body>
  <div id="viewDiv"></div>
  <button onclick = 'DisplayName()'>Results</button>
</body>
‍‍‍‍‍

In your code, the query hasn't started (line 67) or completed (line 60) before you display the variable. You have to wait for the query to complete before you can see the results.