If what you want to do is fit the current markers selection on the screen, you're probably looking for fitBounds method. Also see these two answers:
Thank you, @MrUpsidown.
If you're interested in finding the "middle" of a marker selection without changing zoom level, here's my original answer:
"Finding the center" can be a complex geometrical problem but, in your case, it looks like you want to find the intersection of diagonals of the smallest NS/EW rectangle containing all points.
Which means you should to get the min
and the max
of both lat
and lng
arrays and find the median of those limits, for each array.
// this fails when polygon crosses 180th meridian!
function findCenter(markers) {
const lats = markers.map(m => m.lat);
const lngs = markers.map(m => m.lng);
return {
lat: (Math.min(...lats) + Math.max(...lats)) / 2,
lng: (Math.min(...lngs) + Math.max(...lngs)) / 2
};
}
However, the above code produces wrong results for polygons crossing the 180th meridian, as @MrUpsidown noted. The correct code to include that case is:
function getMiddle(prop, markers) {
let values = markers.map(m => m[prop]);
let min = Math.min(...values);
let max = Math.max(...values);
if (prop === 'lng' && (max - min > 180)) {
values = values.map(val => val < max - 180 ? val + 360 : val);
min = Math.min(...values);
max = Math.max(...values);
}
let result = (min + max) / 2;
if (prop === 'lng' && result > 180) {
result -= 360
}
return result;
}
function findCenter(markers) {
return {
lat: getMiddle('lat', markers),
lng: getMiddle('lng', markers)
}
}
// tests:
console.log(findCenter([
{ lat: 14.692734621176195, lng: 120.9642877585083 },
{ lat: 14.691963317641529, lng: 120.9715473253784 },
{ lat: 14.702160611177580, lng: 120.9621292582138 },
]));
// => { "lat": 14.697061964409555, "lng": 120.96683829179611 }
console.log(findCenter([
{ lat: 50, lng: 45 },
{ lat: 0, lng: 125 },
{ lat: -50, lng: -100 }
]))
// => { "lat": 0, "lng": 152.5 }
The difference between my answer (green) and tugrul's answer (blue) is depicted graphically here: https://q2k0r.csb.app/
As pointed out by @mrupsidown, Google maps API provides utilities to calculate the center of collection of points:
- create a
LatLngBounds
object and extend it from the markers collection
- use
.getCenter()
on the created bounds object.