4

Does anyone know if/how it's possible to restrict/limit the marker position in map?

I want to restrict my marker to a position inside a town (for instance with a 10km radius) and don't allow the user to drag/create a new marker out of that radius limit...

zppinto
  • 287
  • 7
  • 20
  • http://stackoverflow.com/questions/4631382/google-maps-limit-panning – Steve Jul 07 '14 at 13:12
  • That's a possibility... However it doesn't restrict the marker creation to a certain position! Thank you any way ;) – zppinto Jul 07 '14 at 13:37
  • My thinking is that you restrict the entire map view to your area, there by limiting where the user can drop a marker. Maybe thats not suitable for you though. – Steve Jul 07 '14 at 13:39
  • 1) Define a center point. 2) Define a max radius. 3) On `dragend` event of the marker, check the distance between center point and new location. If too far away, place the marker back to its last position (or the center point, that's up to you). – MrUpsidown Jul 07 '14 at 13:40
  • Thank you @MrUpsidown. I think I will take your advise and do something related to it ;) – zppinto Jul 07 '14 at 14:19

1 Answers1

4

In addition to my comment, here is an example using map bounds as boundaries.

The bounds are defined to the map bounds when the map first loads:

bounds = map.getBounds();

Then in the marker dragend event, I check whether the new location falls within the defined bounds, and if not, revert the marker to the last saved position:

google.maps.event.addListener(marker, 'dragend', function () {

    var position = marker.getPosition();
    bounds.contains(position) ? lastPosition = position : marker.setPosition(lastPosition);
});

You can check the below example for a live example (zoom out and drag the marker outside of the original map bounds).

JSFiddle demo

MrUpsidown
  • 21,592
  • 15
  • 77
  • 131
  • Thank you for your answer, however I have found a more restricted approach (http://stackoverflow.com/questions/16708254/adding-click-listener-on-circle-is-not-working). Which have lead me to find `google.maps.Polygon`! I have created my city limits and now it's perfect :) – zppinto Jul 07 '14 at 16:19
  • Yeah sure. Depends what you want. A cirlce (radius), map bounds or custom defined boundaries. Good luck! – MrUpsidown Jul 08 '14 at 07:22