SuRa
SuRa

Reputation: 513

Find if given lat/lng co-ordinates lies inside a square/rectangle

I have 3 set of co-ordinates

  1. Coordinate to check
  2. NorthWest coordinate
  3. SouthEast coordinate

The 2 & 3 are the diagonal for a square/rectangle. I have to find if the given coordinate(1) is lies inside 2&3.

The same question was posted earlier but there are no answers posted. Duplicate Question

Upvotes: 1

Views: 2998

Answers (1)

SuRa
SuRa

Reputation: 513

I got the solution what I was looking for. Got solution from here

/*
* top: north latitude of bounding box.
* left: left longitude of bounding box (western bound). 
* bottom: south latitude of the bounding box.
* right: right longitude of bounding box (eastern bound).
* latitude: latitude of the point to check.
* longitude: longitude of the point to check.
*/
boolean isBounded(double top, double left, 
                  double bottom, double right, 
                  double latitude, double longitude){
        /* Check latitude bounds first. */
        if(top >= latitude && latitude >= bottom){
                /* If your bounding box doesn't wrap 
                   the date line the value
                   must be between the bounds.
                   If your bounding box does wrap the 
                   date line it only needs to be  
                   higher than the left bound or 
                   lower than the right bound. */
            if(left <= right && left <= longitude && longitude <= right){
                return true;
            } else if(left > right && (left <= longitude || longitude <= right)) {
                return true;
            }
        }
        return false;
}

Upvotes: 6

Related Questions