I am trying to get the center of a shape in android. The shape is draw by hand on the map. I have all of the co-ordinates but the mean values are turning out to be trickier than I thought. I want to plot a marker on the mean latitude and longitude.
I have tried summing up the latitude and longitude separately and then dividing by the number of points. This does not give the correct answer. The marker always seems to be trailing behind the draw figure. I have also tried using the implementation but it gives the same answer, a previous SO question, Calculate the center point of multiple latitude/longitude coordinate pairs
The code I have been using:
private void calculateFreeHandPolygonParameters(){
double xValues = 0;
double yValues = 0;
double zValues = 0;
int count = 0;
// linesForPolygon a list of the lines in the polygon
for(Polyline line : linesForPolygon){
for (LatLng point : line.getPoints()) {
xValues += Math.cos(Math.toRadians(point.latitude)) * Math.cos(Math.toRadians(point.longitude));
yValues += Math.cos(Math.toRadians(point.latitude)) * Math.sin(Math.toRadians(point.longitude));
zValues += Math.sin(Math.toRadians(point.latitude));
count++;
}
}
double meanX = xValues/count;
double meanY = yValues/count;
double meanZ = zValues/count;
double centralLongitude = Math.atan2(meanY, meanX);
double centralSquareRoot = Math.sqrt(Math.pow(meanX, 2) + Math.pow(meanX, 2) + Math.pow(meanX, 2));
double centralLatitude = Math.atan2(meanZ, centralSquareRoot);
double latitude = Math.toDegrees(centralLatitude);
double longitude = Math.toDegrees(centralLongitude);
Log.i("MAPS", "Freehand Parameters: x mean -> " + latitude + " y mean -> " + longitude);
testMarker = mMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.title("Polygon center")
.snippet("lat: " + latitude + " long: " + longitude));
}