DEV Community

Cover image for How to Center Multiple Pins for Google Maps API
Elliot Mangini
Elliot Mangini

Posted on

4

How to Center Multiple Pins for Google Maps API

I'll keep this short!

This will work if you're starting with a large number of locations and you have their latitude and longitude.

For this project I was working with React so we are using a helper function to parse a center out of those above items and pass it to the map component.

let centerMath = [0, 0];
locations.map((place) => {
    centerMath[0] += place.latitude;
    centerMath[1] += place.longitude;
}
centerMath[0] = centerMath[0] / locations.length;
centerMath[1] = centerMath[1] / locations.length;
setCenter({
    lat: centerMath[0],
    lng: centerMath[1],
});
Enter fullscreen mode Exit fullscreen mode

Then we pass the state down to the map component and use it here (in my case in the GoogleMap component):

<GoogleMap
zoom={10}
center={center}
options={settings}
>
Enter fullscreen mode Exit fullscreen mode

Feel free to scaffold this directly.

We're basically just adding all the lats and dividing by the number of places, same for longs. If we have two places at 0, 10 and 0, 20 then our center point comes out to be 0, 15. Not too complex but figured it might help someone out!

Cheers
-Elliot/Big Sis

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay