Finds the closest point within a rectangle - Java java.lang

Java examples for java.lang:Math Geometry Shape

Description

Finds the closest point within a rectangle

Demo Code

/*/*from   w ww . ja  v a 2  s. c  o  m*/
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
//package com.java2s;

public class Main {
    /**
     *  Finds the closest point within a rectangle (defined by rMinX, rMinY, rMaxX, rMaxY) to the given (lon, lat) point
     *  the result is provided in closestPt.  When the point is outside the rectangle, the closest point is on an edge
     *  or corner of the rectangle; else, the closest point is the point itself.
     */
    public static void closestPointOnBBox(final double rMinX,
            final double rMinY, final double rMaxX, final double rMaxY,
            final double lon, final double lat, double[] closestPt) {
        assert closestPt != null && closestPt.length == 2;

        closestPt[0] = 0;
        closestPt[1] = 0;

        boolean xSet = true;
        boolean ySet = true;

        if (lon > rMaxX) {
            closestPt[0] = rMaxX;
        } else if (lon < rMinX) {
            closestPt[0] = rMinX;
        } else {
            xSet = false;
        }

        if (lat > rMaxY) {
            closestPt[1] = rMaxY;
        } else if (lat < rMinY) {
            closestPt[1] = rMinY;
        } else {
            ySet = false;
        }

        if (closestPt[0] == 0 && xSet == false) {
            closestPt[0] = lon;
        }

        if (closestPt[1] == 0 && ySet == false) {
            closestPt[1] = lat;
        }
    }
}

Related Tutorials