How to drag and move multiple polygons simultaneously on Google Map

ducdaoo

Lycanus

Posted on May 30, 2023

How to drag and move multiple polygons simultaneously on Google Map

Google map doesn't support multiple dragging on drawn objects, so in this article I'll show you a simple way to make multiple dragging on Google Map.

Moving an object on Google Map as well as we constantly update its path. To dragging and moving multiple objects on map, we just need to update path of these objects.
Assume I have a drawn polygon on Google Map, I want to move the polygon more 10 meters from current position, from west to east. And this is how to calculate a new path for the polygon, when we know moved distance, and moving direction.

const movedDistance = 10; // 10 meters
const heading = 90; // from west to east, heading is 90 degrees

const currentPath = polygonInstance.getPath.getArray();
const newPath = currentPath.map(path => {
 return maps.geometry.spherical.computeOffset(path, movedDistance, heading);
});

// update new paths
polygonInstance.setPath(newPath);
Enter fullscreen mode Exit fullscreen mode

The implement code above is quite OK, but there is a problem, how do we know moved distance and heading value when we drag and move a polygon on map? It's quite simple, we just need a start point(startLatLng) and end point(endLatLng), pass these values to these two methods computeHeading and computeDistanceBetween. We can obtain startLatLng and endLatLng through dragstart and drag event of polygon.

const movedDistance = maps.geometry.spherical.computeDistanceBetween(startLatLng, endLatLng);
const heading = maps.geometry.spherical.computeHeading(startLatLng, endLatLng);
Enter fullscreen mode Exit fullscreen mode

Here is my implemented code, let see in this fiddle link.

💖 💪 🙅 🚩
ducdaoo
Lycanus

Posted on May 30, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related