How to detect if a point is in a Circle?

前端 未结 6 776
广开言路
广开言路 2020-12-02 00:26

How can I test if a LatLng point is within the bounds of a circle? (Google Maps JavaScript v3)

The getBounds() method returns the bounding box for the circle, which

6条回答
  •  生来不讨喜
    2020-12-02 00:59

    Something like this should do the trick (code not tested):

    public boolean pointInCircle(Circle c, LatLng coord) {
      Rectangle r = c.getBounds();
      double rectX = r.getX();
      double rectY = r.getY();
      double rectWidth = r.getWidth();
      double rectHeight = r.getHeight();
    
      double circleCenterX = rectX + rectWidth/2;
      double circleCenterY = rectY + rectHeight/2;
    
      double lat = coord.getLatitude();
      double lon = coord.getLongitude();
    
      // Point in circle if (x−h)^2 + (y−k)^2 <= r^2
      double rSquared = Math.pow(rectWidth/2, 2);
      double point = Math.pow(lat - circleCenterX, 2) + Math.pow(lon - circleCenterY, 2);
    
      return (point <= rSquared) ? true : false;
    }
    

提交回复
热议问题