1. 程式人生 > >依據地圖上的經緯度座標計算某個點到多邊形各邊的距離

依據地圖上的經緯度座標計算某個點到多邊形各邊的距離

http://www.th2w.com/article/85


依據地圖上的經緯度座標計算某個點到多邊形各邊的距離

最近公司有一個需求:依據地圖上的經緯度座標計算某個點到多邊形各邊的距離。 主要原理:

  1. 依據當前點p和多邊形相鄰兩點(pb, pe)組成三角形
  2. 由於是座標系,比用海倫公式要好
  3. 用座標向量差求得兩點構成的線l與X座標的餘弦值平方()
  4. 依據點pb和pe計算出tan值,依據tan值計算出線l與p點緯度線的交集值
  5. 計算出p點到交集的距離,作為y軸向量差
  6. 依據餘弦計算出直線距離

具體檢視java實現程式碼:

package distance;

import java.math.BigDecimal;

public class Point {

    private BigDecimal x;

    private BigDecimal y;

    public Point (double y, double x) {
        this.x = new BigDecimal(x);
        this.y = new BigDecimal(y);
    }

    public Point (BigDecimal y, BigDecimal x) {
        this.x = x;
        this.y = y;
    }

    /**
     * 當前點和頂點之間構成的餘弦值平方
     * 
     * @param p
     * @return
     */
    private BigDecimal cos2(Point p) {
        BigDecimal vector2 = (p.x.subtract(x).pow(2)).add(p.y.subtract(y).pow(2));
        return (p.x.subtract(x).pow(2)).divide(vector2, 11, BigDecimal.ROUND_HALF_DOWN);
    }

    /**
     * 當前點到頂點之間的Y向量差
     * 
     * @param p
     * @return
     */
    private BigDecimal toY(Point p) {
        return p.y.subtract(y);
    }

    /**
     * 當前點到頂點之間的x向量差
     * 
     * @param p
     * @return
     */
    private BigDecimal toX(Point p) {
        return p.x.subtract(x);
    }

    /**
     * 1度多少米
     * @return
     */
    private BigDecimal itude1() {
        return new BigDecimal(Math.cos(y.doubleValue())).multiply(new BigDecimal(111194.92474777778)).abs();
    }

    /**
     * 當前頂點到兩點之間的距離
     * 
     * @param pb 起始點
     * @param pe 結束點
     * @return
     */
    public double distance(Point pb, Point pe) {
        if(pe.toX(pb).doubleValue() == 0) {
            BigDecimal dist2 = pe.toY(this).pow(2);
            return itude1().multiply(new BigDecimal(Math.sqrt(dist2.doubleValue()))).doubleValue();
        } else {
            BigDecimal vector = pe.toY(pb).multiply(toX(pb)).divide(pe.toX(pb), 11, BigDecimal.ROUND_HALF_DOWN).subtract(toY(pb));
            BigDecimal dist2 = pb.cos2(pe).multiply(vector.pow(2));
            return itude1().multiply(new BigDecimal(Math.sqrt(dist2.doubleValue()))).doubleValue();
        }
    } 

    public static void main(String[] args) {
        // 地圖上畫一個多邊形
        Point[] points = {
                new Point(40.049409, 116.300804), 
                new Point(40.052924, 116.309191), 
                new Point(40.054781, 116.307524), 
                new Point(40.052312, 116.300339)
        };
        // 地圖多邊形內隨機某一點
        Point p = new Point(40.050740, 116.302464);

        // 當前點到多邊形各邊的距離
        for (int i = 0; i < points.length; i++) {
            System.out.println("distance=" + p.distance(points[i], points[i == points.length - 1 ? 0 : i+1]) + "米");
        }
    }
}