waiting for deferred to complete in esri javascript api before continuing with code execution - labelPoints

I'm encountering an issue with obtaining my labelPoints before completing the rest of my code. It seems to be related to a deferred/callback problem that I can't quite grasp, and I couldn't find many examples using the esri javascript api.

In essence, I utilize centroids for creating a click point from an address search, but for irregular shaped polygons, I need to use labelPoints to ensure the point falls within the polygon.

The executeQueries() function works fine in the if statement, but in the else block it doesn't execute correctly because the labelPoints retrieval happens after executeQueries(). I attempted to use .on("label-points-complete") to trigger the executeQueries(), but it doesn't seem to work. I just want to get the geometry from the labelPoint before proceeding further. I've tried numerous methods without success. Any suggestions are appreciated. Thank you.

function symbolizeFoundFeatures(featureSet) {
    //If we have a result set
    if (featureSet.features.length > 0) {
    //Highlight the feature
    var polygonJson = { "rings": featureSet.features[0].geometry.rings, "spatialReference": map.spatialReference };
    var selectedGeometry = featureSet.features[0].geometry;
    searchedGraphic = map.graphics.add(new esri.Graphic(new esri.geometry.Polygon(polygonJson), 
        new esri.symbol.SimpleFillSymbol(
            esri.symbol.SimpleLineSymbol.STYLE_SOLID,
            new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID,
            new esri.Color([0, 0, 0, 1]), 1),
            new esri.Color([255, 0, 0, 0.2]))
        ));

    selectedCentroid = searchedGraphic.geometry.getExtent().getCenter();
    var markerSymbol = map.graphics.add(new SimpleMarkerSymbol(SimpleMarkerSymbol.STYLE_SQUARE, 10,
        new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID,
        new Color([255, 0, 0]), 1),
        new Color([0, 255, 0, 0.25])
    ));
    var searchedGraphicPoint = new Graphic(selectedCentroid, markerSymbol);

//the if here runs everything perfectly
    if (searchedGraphic.geometry.contains(selectedCentroid)) {
        useThisPointToInitiateClick = selectedCentroid;
        executeFromSearchedPoint = "Yes";
        executeQueries();
    }
    else 
      {geometryService.labelPoints([searchedGraphic.geometry], function (labelPoints) {
         console.log("in contains else ");
         var searchedGraphicLabelPoint = new Graphic(labelPoints[0], markerSymbol);
         map.graphics.add(searchedGraphicLabelPoint);
         useThisPointToInitiateClick = labelPoints[0];
         console.log(useThisPointToInitiateClick);
         executeFromSearchedPoint = "Yes";
         console.log("before execute queries, after adding center points");
     });
     }
     }
}

geometryService.on("label-points-complete", function (evt) {
     console.log("hi");
     console.log(executeFromSearchedPoint);
     executeQueries();
});

Answer №1

Would it suffice to simply invoke the executeQueries() function within the labelPoints callback?

Additionally, you can eliminate the need for

geometryService.on("label-points-complete

else 
      {geometryService.labelPoints([searchedGraphic.geometry], function (labelPoints) {
         console.log("in contains else ");
         var searchedGraphicLabelPoint = new Graphic(labelPoints[0], markerSymbol);
         map.graphics.add(searchedGraphicLabelPoint);
         useThisPointToInitiateClick = labelPoints[0];
         console.log(useThisPointToInitiateClick);
         executeFromSearchedPoint = "Yes";
         console.log("before execute queries, after adding center points");
executeQueries();
     });
     }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Custom dropdown feature in Vue-tables2

Is there a way to customize the select dropdown style in vue-tables2 table? I am trying to change the entire template of the dropdown, not just add CSS classes. My custom template includes additional elements like span and div tags that need to be incorpor ...

Methods for adding a line to an array

I am currently working on a loop where I need to populate my array called photos: $scope.photos = []; var str = data.data.Photos; var res = str.split('|'); angular.forEach(res, function (item) { ...

What is the process for incorporating a full-page blog into a blog preview?

I customized a template, but there is a blog section within the div that I am struggling to replicate. Here is the test website for reference: Below is the HTML code for the blog section: <!-- Blog Start --> <section class="section bg ...

Send the JSON output of a MySQL query as an argument to my EJS template in a Node.js/Express application

I've been using res.json(rows) to display my users on the screen, but now I want to pass the object obtained from the query to an ejs file for display. However, when I try to do this as shown in my code below, the passed object becomes a string and I& ...

What methods does GitHub use to determine my login status?

I removed the localStorage storage, but it didn't make a difference. I'm curious - does GitHub store IP addresses of logged-in users in a database, or maybe in browser headers? ...

Printing dynamic data

When the print button is clicked, I need to print dynamically generated data from a table that has an ID. The table data (td and tr) is dynamically generated. I have successfully retrieved the table data and attempted to print everything using window.prin ...

Embracing the beauty of incorporating nested quotations

I've been experimenting with jquery's append functions lately. I'm adding a substantial amount of html, specifically a button with an onclick event function. It might sound complicated, but due to some technical restrictions, this is my onl ...

Transmit data from Raspberry Pi to Apache Server with strong security measures

Utilizing a Raspberry Pi to collect temperature data and store it in a file Running on a virtual machine, the server uses Apache to host a website (comprised of HTML, PHP, and JavaScript) displaying a graph based on this data I am seeking a secure method ...

Obtain unique identifiers for the purpose of sorting the items

While utilizing Nuxt.js, I am fetching random images from URLs structured like this: http://www.randomimage.com?ID=myId To display 2 pictures, I use the following methods: getRandomArbitrary(min, max) { return this.numb = Math.floor(Math.random() * ...

Receive AJAX aid for PHP/MySQL dynamic dropdown menu implementation

My goal is to dynamically populate a second drop-down menu based on the selection made in the first drop-down. The first drop-down contains a list of tables from my database, and the second drop-down should display providers associated with the selected ta ...

What impact does changing the Device Language have on a heading?

At the top of an html page, I have the word "Color" in a heading. If a user's device is set to British English, I would like the text to automatically switch to "Colour". What is the best way to accomplish this with minimal Javascript? ...

Steps to fix ESlint warning: Avoid using assignment in return Statement (no-return-assign)

In my React application, I am utilizing the package found at https://github.com/appleboy/react-recaptcha to create a Recaptcha component. Below is an image of what the component looks like, along with an eslint warning: The definition of this.recaptchaRe ...

Store the text area content as a JSON object

What is the best way to store the content of a textarea in JSON format? I am currently working on a project where I have a textarea element and I need to save its value into a JavaScript object. Everything is functioning correctly except when 'enter ...

Ways to compare two arrays based on a specific field using JavaScript

I have two arrays, known as array 'a' and array 'b'. var a = [ [1,'jake','abc',0 ], ['r', 'jenny','dbf',0] , ['r', 'white','dbf',0] ] var b = [ ['s&ap ...

Exploring the Worldwide Influence of TypeScript, React, and Material-UI

I am currently following an official tutorial on creating a global theme for my app. In my root component, I am setting up the global theme like this: const themeInstance = { backgroundColor: 'cadetblue' } render ( <ThemeProvider theme ...

Using Typescript to Import One Namespace into Another Namespace

Is it possible to export a namespace from one typescript .d.ts file and then import that namespace into another .d.ts file where it is utilized inside of a namespace? For instance: namespace_export.d.ts export namespace Foo { interface foo { ...

Securing NextJS API Routes with API Key Authorization

I'm developing an app in NextJS 13 that utilizes API routes, and I aim to secure them against any unauthorized access from external functions. While my app integrates Auth0, there is no strict requirement for protection since unregistered individuals ...

Ways to create a clickable anchor tag without using any text

I am currently designing my own website and incorporating links to various social media platforms using icons. However, I am facing an issue where the links are not clickable. For a detailed look at my problem, you can refer to this JSFiddle: http://jsfid ...

Rendering Local HTML with local styling and scripts in React Native Webview

I am having trouble loading a local HTML, CSS, and JS file in my React Native webview. The CSS is not being applied to the HTML. Here is my folder structure: My HTML file, along with CSS, images, and JS file are all placed in the following app folder stru ...

React infinite scroller - component fails to work when initial items are insufficiently loaded

In my Next.js app, I am dealing with a large firestore database containing many book objects. To filter these books based on keywords in their title, category, author, etc., I have implemented a searchbar. Due to the sheer volume of books, I am utilizing l ...