How to find the center of an area element with JavaScript

In a recent project I was working on a script interacting with an image map consisting of irregular areas and needed to find the center of each of these areas.

I couldn’t find a function to do that so I wrote my own. It’s pretty simple, but in case anyone else needs this I thought I’d share.

The function takes two parameters:

The type of shape (circle, poly, or rect)
A comma-separated list of coordinate values

The values are just the text values of the shape and coords attributes of the area element.

The function looks like this:

function getAreaCenter(shape, coords) {
    var coordsArray = coords.split(','),
        center = [];
    if (shape == 'circle') {
        // For circle areas the center is given by the first two values
        center = [coordsArray[0], coordsArray[1]];
    } else {
        // For rect and poly areas we need to loop through the coordinates
        var coord,
            minX = maxX = parseInt(coordsArray[0], 10),
            minY = maxY = parseInt(coordsArray[1], 10);
        for (var i = 0, l = coordsArray.length; i < l; i++) {
            coord = parseInt(coordsArray[i], 10);
            if (i%2 == 0) { // Even values are X coordinates
                if (coord < minX) {
                    minX = coord;
                } else if (coord > maxX) {
                    maxX = coord;
            } else { // Odd values are Y coordinates
                if (coord < minY) {
                    minY = coord;
                } else if (coord > maxY) {
                    maxY = coord;
        center = [parseInt((minX + maxX) / 2, 10), parseInt((minY + maxY) / 2, 10)];

It returns an array with two values – the X center and the Y center. Here’s an example of calling the function:

var area = document.getElementById('area-1');
var center = getAreaCenter(area.getAttribute('shape'), area.getAttribute('coords'));
alert('X-center: ' + center[0] + ', Y-center: ' + center[1]);

In my use case I looped through the area elements of a particular map element and stored the center coordinates in a custom attribute on each area element for easy access later on.

Hope it’s of use to someone.

Posted on April 18, 2011 in JavaScript

Comments are disabled for this post (read why), but if you have spotted an error or have additional info that you think should be in this post, feel free to contact me.