Is it possible to calculate width and height for each poly area on image map using coords?
I have an image and use image map with multiple different sized polys. I need to find center point each one.
Is it possible to calculate width and height for each poly area on image map using coords?
I have an image and use image map with multiple different sized polys. I need to find center point each one.
To find the center point, you need to find the minimum and maximum X and Y coordinates of the polygon, and then take the midpoint of each to get the average center point. Here's a function that will do this for an array of imagemap areas. The function accepts an array rather than just one area in case you need a center point from several areas, as are typical in geographical image maps.
Working example here that will draw a circle on the center point of the chose US state: http://jsfiddle.net/jamietre/6ABfa/
/* Calculate the centermost point of an array of areas
@param {element[]} areas an array of area elements
@returns {object} {x,y} coords of the center point
*/
function calculateCenterPoint(areas) {
var maxX = 0,
minX = Infinity,
maxY = 0,
minY = Infinity;
// note: using Array.prototype.forEach instead of calling forEach directly
// on "areas" so it will work with array-like objects, e.g. jQuery
Array.prototype.forEach.call(areas, function (e) {
var i = 0,
coords = e.getAttribute('coords').split(',');
while (i < coords.length) {
var x = parseInt(coords[i++],10),
y = parseInt(coords[i++],10);
if (x < minX) minX = x;
else if (x > maxX) maxX = x;
if (y < minY) minY = y;
else if (y > maxY) maxY = y;
}
});
return {
x: minX + (maxX - minX) / 2,
y: minY + (maxY - minY) / 2
};
}