Skip to content

Instantly share code, notes, and snippets.

@joseadrian
Last active March 24, 2021 15:12
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save joseadrian/7492128 to your computer and use it in GitHub Desktop.
Save joseadrian/7492128 to your computer and use it in GitHub Desktop.
Google Maps. Detect if one of the points on the polyline paths intersects a circle

Working example

First, it checks if one of the points of the path is inside the circle. Then, checks every segment of the path and calculates the nearest point of the segment to the circle; if it's less than the circle radius, then, there is an intersection.

To Do

  • Better performance by reducing the numbers of segments. Only the closests one depending on the points.
  • Remove map as argument

Help From Circle line collision detection

(function(){
var polyline = new google.maps.Polyline();
google.maps.Polyline.prototype.closestDistanceToSegment = function(center, segment)
{
var firstPoint, lastPoint, A, B, C, D, E, distanceAB, t, projection = this.getMap().getProjection();
// The other extreme of the path
lastPoint = segment[0];
// One extreme of the path
firstPoint = segment[1];
// C
// |\
// | \
// | \
// |_ _\
// A B
//
// Transform to points
A = projection.fromLatLngToPoint(lastPoint);
B = projection.fromLatLngToPoint(firstPoint);
C = projection.fromLatLngToPoint(center);
// Calculte distance between A and B
distanceAB = Math.sqrt( Math.pow(A.x-B.x, 2)+Math.pow(A.y -B.y, 2) );
// Compute the direction vector D from A to B
D = { x: (B.x-A.x)/distanceAB, y: (B.y-A.y)/distanceAB };
t = D.x*(C.x-A.x) + D.y*(C.y-A.y);
// LatLng of the point
E = projection.fromPointToLatLng({ x: t*D.x+A.x, y: t*D.y+A.y });
polyline.setPath(segment);
// En la docuemntacion poly.containsLocation sirve para Polygonos.
// poly.isLocationOnEdge no es muy preciso
if(google.maps.geometry.poly.containsLocation(E, polyline))
{
return google.maps.geometry.spherical.computeDistanceBetween(E, center);
}
return Number.POSITIVE_INFINITY;
}
google.maps.Polyline.prototype.intersectsCircle = function(circle)
{
var poly = this,
path = poly.getPath(),
totalPoints = path.getLength(),
center = circle.getCenter(),
radius = circle.getRadius(),
intersect = false,
indice = 0;
while(indice < totalPoints && intersect === false){
var point = path.getAt(indice++);
if(google.maps.geometry.spherical.computeDistanceBetween(center, point) <= radius || 
(indice < totalPoints && poly.closestDistanceToSegment(center, [point, path.getAt(indice)]) <= radius))
{
intersect = true;
}
}
return intersect;
}
})()
@shobishani
Copy link

It's very good solution. Thanks for sharing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment