Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

dilfdo's avatar

calculating center point using geo latitude and longitude values

i want to calculate the center point location from series of longitude latitude values. please advice

0 likes
7 replies
Prullenbak's avatar

You can just take the average of the latitude values, and the average of the longitude values. That should give you the (approximate) center of them.

paradox's avatar

@dilfdo did you study math hard? https://en.wikipedia.org/wiki/Centroid ;-) but seriously, if you use google api (I assume) some clients specifically JS offers getCenter method (compare with getCenter method on LatLngBounds objects presented here: http://stackoverflow.com/a/3082334 )

To make a calculation in php however just browse in github repos how others did it. First hit: https://raw.githubusercontent.com/robo47/PHP-Google-Maps/master/PHPGoogleMaps/Overlay/Polygon.php

dilfdo's avatar

@Prullenbak will getting average values of latitude and longitude seperatly give correct coordinates??

Prullenbak's avatar

It will, but it will ignore the fact that the earth isn't flat ;) In most practical situations (you're not landing spaceships, are you? ;) ), it will be just fine.

$lat = 0.0;
$lon = 0.0;
foreach ($markers as $marker) {
    $lat += $marker->lat; // or $marker['lat'] I don't remember
    $lon += $marker->lon; // or $marker['lon'] ?
}

$centerlat = $lat / count($markers);
$centerlon = $lon / count($markers);
1 like
dilfdo's avatar

@Prullenbak : in my case i need some accurate data since those data im passing to mobile app for users to find locations :) , please advice

Prullenbak's avatar

Yeah...But how accurate do you need? If the points aren't really really far apart, the deviation will be very small (the earth isn't flat. But a town is, sort of). You're working with users' GPS anyway, so your data will never be accurate. For normal location based apps, I believe this way of calculating the center will work just fine.

Prullenbak's avatar

It looks like you're getting all the markers within a radius around a certain point, correct?

If that's returning an array/collection of markers, you can loop through those the way I showed and you get the center of those markers.

Please or to participate in this conversation.