Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drag (move) a polygon using Google Maps v3

The Google Maps API for a Polygon does not offer a drag method.

What would be an efficient way of implementing such a feature (i.e., sufficiently optimised so that it would not kill a four year old laptop)?

Thank you!

like image 384
Dave Jarvis Avatar asked Jun 24 '10 22:06

Dave Jarvis


People also ask

How do I move a polygon in Google Maps?

In Google My Maps, you can click and drag polygons.

How do you drag a marker on Google Maps?

You can allow users to move a marker on the map by setting the marker's draggable property to true .


1 Answers

I found the Google Maps V2 Polygon Implementation to be very limiting for the needs I have had and solved it by creating a custom overlay. My group is currently stuck on IE6 so I have yet to migrate over to Google Maps V3 - but taking a quick look at the API shows that you could probably do a similar thing that I did in V2 with V3.

Essentially the idea is:

  1. Create a Custom Overlay
  2. Populate it with your own SVG/VML Polygons and attach a drag event to this custom polygon object

Custom Overlays:

Here is some information to get you started on making your own custom overlay:

http://code.google.com/apis/maps/documentation/javascript/overlays.html#CustomOverlays


Creating your own "Dragable" Polygon Object:

Once you get that down you'll want to add your own polygons to the custom overlay instead of using GPolygons. I went through the painful process of learning SVG/VML and writing a library to bridge SVG/VML together - you could do that, but I would recommend starting by trying to use another library such as Raphaël.

http://raphaeljs.com/

Using Raphaël will save you a whole lot of time trying to figure out how to get cross-browser Vector Graphic (Polygon) functionality - and best of all it supports drag events already, here is an example from their library:

http://raphaeljs.com/graffle.html

Once you have a custom overlay and you are able to throw some Raphaël objects onto it the last step is to translate the coordinates you want from a Lat/Lng value to a Pixel value. This is available in the MapCanvasProjection of V3:

http://code.google.com/apis/maps/documentation/javascript/reference.html#MapCanvasProjection

You can use fromLatLngToDivPixel to figure out what the actual pixel values are for the points on your Raphael polygon, draw it, then add it to the overlay with a drag event.

like image 124
John Avatar answered Oct 12 '22 01:10

John