Finding center of set of coordinates using Java

4.6k views Asked by At

I'm using Twitter4J to retrieve a user's place from his/her profile. I have a set of geo-coordinates forming a polygon bounds (normally 4 or more coordinates) using this call:

// Status tweet
Place place = tweet.getPlace();
GeoLocation[][] box = place.getBoundingBoxCoordinates();

Is there a way to compute the center (or near-center, or at least a point contained) of this region / polygon / boundary? Is there a Java API for this?

Is there a Java equivalent of this JavaScript code taken from this post:

var bounds = new google.maps.LatLngBounds();
bounds.extend(results[0].geometry.location);
var center = bounds.getCenter();
2

There are 2 answers

0
AudioBubble On BEST ANSWER

A simple way is:

centerLatitude = ( min(latitude) + max(latitude) ) / 2
centerLongitude = ( min(longitude) + max(longitude) ) / 2
0
Jan On

Extending saka's answer (which is the center of the bounding box) you can also iterate over all coordinates and calculate the average of latitude and longitude. The advantage is that outliers don't move the center as much as with the bounding-box approach.

If outliers are not an issue, another way would be to first calculate the convex hull and then its center. You can easily calculate it with a topology library like JTS: http://tsusiatsoftware.net/jts/javadoc/com/vividsolutions/jts/algorithm/ConvexHull.html

Geometry hull = new ConvexHull(coordinates, new GeometryFactory());
Point center = hull.getCentroid();

This gives a better result if your input data is not axis-symmetric, for example rather a triangle than a rectangle or circle.