I have a scenario, in which i need to restrict the user to move the marker only for 800 mts, from the given position. I am using React and Google Maps.
Kindly provide some inputs.
I have a scenario, in which i need to restrict the user to move the marker only for 800 mts, from the given position. I am using React and Google Maps.
Kindly provide some inputs.
Can you explain further your use case? Assuming that you initially have a marker and you would like to only allow pinning your marker 800 meters away from the center you set, you can use a draggable marker with eventListener on dragend. Once the marker drag ends, you will then get the coordinates of the new position of the marker. You will use this coordinate and the coordinate of the center to calculate if the distance between them is greater than 800m using computeDistanceBetween() of the Geometry library. You will use a conditional statement to check if the distance is within 800m, you will pin that marker to that coordinate and if it is greater than 800m, you will put an alert about it and pin the marker to the previous pinned position.
Here's a code snippet:
//markerA is the center
let markerA = new window.google.maps.Marker({
position: { lat: 41.0082, lng: 28.9784 },
map: map,
label:"A",
});
//markerB is the draggable marker
let markerB = new window.google.maps.Marker({
position: { lat: 41.0072, lng: 28.9784 },
map: map,
label:"B",
draggable:true,
});
//previousB will be the variable that hold previous coordinate of markerB
let previousB;
//eventlistener for markerB that listens to the dragend
markerB.addListener("dragend", function (endOfDrag) {
let newLat = endOfDrag.latLng;
//using computeDistanceBetween() to get the distance
let dist = google.maps.geometry.spherical.computeDistanceBetween(
map.center,
newLat
);
//conditional statement
if (dist <= 800) {
alert("Coordinate is inside 800 meters!");
//set the new position to previousB variable
previousB = endOfDrag.latLng;
} else {
alert("Coordinate is more than 800 meters away!");
//pin the markerB back to previous position
markerB.setPosition(previousB)
}
});
Here is a sample reactjs code that implements this.