1

I place a Marker on my map with draggable property true. I want to restrict moving marker not more then 500 meters from original position. How can I do it? Is there a better way that I tried?

I tried with drag event. I measure distance with code I found on SO. But I don't know how can I prevent drag. I try with returning false, try to view if function parameter has cancel or something like that.

google.maps.event.addListener(marker, 'drag', function(e) 
{
    var distance = Application.getMapDistance(data[0].geometry.location, marker.getPosition());
    document.title = distance;
    if (distance > 500)
        return false; //not working, e has no cancel or something like that
});

Edit:

Apparently someone is not happy with my question. Yes the basic logic would be to set google marker position to last good, but this way, marker flicker when it is moved outside the bounds. I am pretty sure Google can do better then this.

google.maps.event.addListener(marker, 'drag', function(e) 
        {
            var distance = Application.getMapDistance(data[0].geometry.location, marker.getPosition());
            document.title = distance;
            if (distance > 500)
                marker.setPosition(lastGoodPosition);
            else
                lastGoodPosition = marker.getPosition();
        });
Community
  • 1
  • 1
Makla
  • 7,975
  • 9
  • 52
  • 118

1 Answers1

2

use 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);

});

set zoom level like that initial map have limit as per your requirement

see a demo on http://jsfiddle.net/upsidown/89DJC/

  • bounds will get me an square, but I need a circle (radius 500m). Dragend is not the solution I am searching for, because it would confuse the user, why marker changed. Thanks anyway. – Makla Oct 19 '16 at 05:13