javascriptDiscover the location of the central point within a polygon

I have stumbled upon a helpful resource that explains how to discover the central point of a polygon (and here in JavaScript):

If you want to see a real-life example, check out this jsfiddle demo.

Let's work with this specific polygon:

var polygon = [
     {'x':770, 'y':400},
     {'x':529, 'y':643},
     {'x':320, 'y':494},
     {'x':424, 'y':381},
     {'x':459, 'y':369}
];

In order to find the center point, utilize the following code:

var con = new Contour();
    con.pts = polygon;
    document.write(con.centroid)

However, I'm encountering an issue where con.centroid is returning as undefined.

If anyone can provide guidance on what might be going wrong, it would be greatly appreciated!

Answer №1

Check out this updated version with the necessary fixes: jsfiddle

I noticed a few errors in your code: - Firstly, you declared Contour and Point after calling them, which caused issues with their usage. - Additionally, you treated centroid as a property instead of a function by not including parentheses () after it. - Lastly, when passing values to the point function within the return value of centroid, x and y should be separate arguments rather than an object.

Answer №2

In order to ensure the proper creation of your "new Contour", it is essential that you define all the necessary components beforehand. Additionally, keep in mind that centroid is a function and should be invoked using con.centroid(). It appears that you desire this function to return a "point", but there may be a better approach to accomplish that. For further insights on this matter, please refer to this resource: http://jsfiddle.net/SsCux/4/

Note: There might be an error in the area calculation.

Answer №3

It seems like you are initializing the Contour constructor before defining its prototype. A better approach would be to move the document.write function call to the end of the code snippet in the provided jsfiddle.

In addition, don't forget to actually use the centroid function that you have defined:

var c = con.centroid();
document.write( c.x );
document.write( c.y );

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

Why am I seeing back-end console errors that are related to my front-end?

Recently, I encountered an error message that prevents me from using 'import' in my front end code when trying to execute 'node index'. This issue never occurred before, and it only arose when I returned to this project. In my backend ...

Operating with a multidimensional entity

I am aiming for an object structure like this: {"Red 1":53,"Blue 2":26,"Green 3":25} Based on the following example: I attempted to push data from within .each loop into the object. However, due to its multidimensional nature, I'm uncertain how to ...

Troubleshooting Timeout Problems with Selebiun Crawler in C#

I am encountering an error while running the following code. public void GetCategoriesSelenium() { string javascript = System.IO.File.ReadAllText(@"GetCategory.js"); CrawlerWebSeleniumJS.ExecuteScript("var finished;"); ...

I'm running into some issues with flexbox and I'm in need of some assistance to find

I positioned two divs next to one another, but instead of each taking up 100vw, they are both sharing 50% of the available space. Is there a solution for this issue? Thank you. Page Image import type { AppProps } from "next/app"; import "./global.cs ...

When attempting to retrieve information using the findById(''), the process became frozen

When attempting to retrieve data using findById(), I'm encountering a problem. If I provide a correct ObjectID, the data is returned successfully. However, if I use an invalid ObjectID or an empty string, it gets stuck. If findById() is called with a ...

Is there a way to conceal the parameters in the PHP GET method?

How to convert PHP GET method URL to a cleaner format? example.com/example.php?name=45 to example.com/example.php/45 Is it possible to achieve this using the .htaccess file? ...

Getting the chosen option from a dropdown list mapped in ReactJS

I am working on a dropdown select option that is linked to the data of an array object called 'template_titles'. Currently, the value in the dropdown corresponds to the title in the object. My goal is to be able to extract and use the selected va ...

Storing data using mongoose does not alter the existing information

I encountered an issue with my code while trying to update an object fetched from a MongoDB. The object contains a map with an array, and I am pushing new values to that array within the map successfully. However, even though the object itself reflects the ...

How do I find the child elements within a parent node?

I am currently utilizing a jquery plugin that has rendered the following HTML layout in the browser: <html> <body> <div class="mce-container-body"> ... <input type="text" id="textedit01"> ... </di ...

What is the best way to execute two asynchronous calls sequentially in JavaScript?

When using a common generic function for AJAX calls, the initial request retrieves all data from the server and maintains it within local scope. However, subsequent requests are still hitting the server, even when the data is already available locally. Thi ...

Dynamically Generate Nested Objects in JavaScript

I have an object that is currently empty and I am looking to dynamically create a nested object within it. const obj = {} obj["test1"]["test1.1"] = x //initialize to some variable However, I encountered this error message: Uncaught Typ ...

Retrieve a zip file using React and Node from a RESTful API

I have an application built with React and Node where I have a table that includes a download button. Clicking the download button triggers a request to my Node app, which in turn should call a REST API to download a zip file directly into the browser. In ...

Changing the background color using jQuery switch case statement

I am attempting to utilize jquery to dynamically change the background image of a webpage based on different cases in a JavaScript switch statement. I have completed three steps: 1) Included this script tag in my HTML document: <script src="http://co ...

Enclose every line of the paragraph within a <span> element

My <div> element is configured to display a paragraph without any line breaks, similar to the example below: <div> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dum ...

I am continuously encountering an error message saying [$injector:modulerr] while working with AngularJS

I've been reviewing my JavaScript code thoroughly, but I can't seem to pinpoint any major issues. The error message I'm encountering is as follows: Uncaught Error: [$injector:modulerr] Failed to instantiate module careApp due to: Error: [$i ...

Enhance Vaadin 14: Automatically adjust TextArea size when window is resized

Using Vaadin 14.1.19 in a project called "My Starter Project," I attempted to create a TextArea that supports multiple lines. Initially, everything seemed fine, but upon resizing the TextArea, it failed to adjust the number of visible lines. Here is the co ...

Can someone provide a method to access the namespace of an Angular controller when utilizing the "Controller As" format?

Imagine you have an AngularJS ngController directive set up like this: <div ng-controller="SomeCtrl as herpderp">…</div> Is there a way to extract the namespace ("herpderp") from within the SomeCtrl controller itself? This could be useful f ...

Sorting through items based on several URL parameters

In an effort to be concise yet clear, I am working on an ecommerce website using Next.js and Shopify. This site features products that need to be filterable based on certain attributes. I retrieve products from the Shopify API, each with its own Product Ty ...

Implementing Node.js with browser cache and handling 304 responses

I am currently in the process of creating a single page application with a standard HTML layout as shown below: <html> <head> <title>...</title> <link rel="stylesheet" media="all" type="text/css" href="css/main.css"> ...

The functionality of Webdriver.waitUntil is not meeting the expected outcomes

I'm currently utilizing webdriverio version 4.5: ./node_modules/.bin/wdio -v v4.5.2 In my scenario, I am in need of waiting for the existence of a specific element and handling the situation if it doesn't exist. Here is an example code snippet ...