Google Maps

Detecting Polyline and Circle collision(?)

by joseadrian

HTML

<script src="http://maps.google.com/maps/api/js?libraries=geometry&amp;sensor=false&amp;.js"></script>
<div id="mapa"></div>
Create a path clicking on the map.
A circle is added to the last point. If you move it and it intersects the polyline, it will turn yellow, if not, black.

CSS

#mapa{
  width: 100%;
  height: 400px;
}

JavaScript

(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, map = this.getMap();
    
    // The other extreme of the path
    lastPoint  = segment[0];
    
    // One extreme of the path
    firstPoint = segment[1];
        
    //  C
    //  |\ 
    //  | \
    //  |  \
    //  |_ _\
    //  A    B
    //
    // Transform to points
    A = map.getProjection().fromLatLngToPoint(lastPoint);  
    B = map.getProjection().fromLatLngToPoint(firstPoint);
    C = map.getProjection().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 = map.getProjection().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;
        
    path.forEach(function(point, index) {
      if(intersect === true) return;
      
      if(google.maps.geometry.spherical.computeDistanceBetween(center, point) <= radius || 
        (index < totalPoints - 1 && poly.closestDistanceToSegment(center, [point, path.getAt(index+1)]) <= radius))
     ...