There is, as far as I know, no easy way to do it. Polylines only have the locations (latLng objects) that you initially pass them and that is it.
So, with this in mind, you can take two approaches:
- Instead of a Polyline, you can draw a Polygon.
- Change your Polyline to include more points.
Polygon
With this approach, you would have to draw a very thin polygon, thin enough to look like a line.
Wit this approach you can easily check if the marker is inside the polygon by using the containsLocation()
method, and if not, set its new position to inside the Polygon.
The drawback is that your Polygon needs to be very, very thin, and you need to set a width for the line. If the width is too big, the dragging will look inaccurate, and if it is too small you may miss it.
Polyline
With this approach, you would have to add multiple points to the polyline, and then move the marker to one of those points every time it went out.
This way there is no need to create a width to calculate the line, but you need to calculate dozens if not hundreds of extra points automatically, and then add them to the Polyline.
Both solutions would work, and both have pros and cons. In the end, it pretty much goes around the which poison do you prefer old saying.
Extra
Theory aside, I did find a good example for the Polylines strategy (kudos to @geocodezip for the comment and @BradBarrow for the response).