import { Geometry , CoordinateType } from "./geometry" ; import { Bound } from "../util/bound" ; import { Projection } from "../projection/projection" ; import { FillSymbol , SimpleFillSymbol , Symbol } from "../symbol/symbol" ; import { WebMercator } from "../projection/web-mercator" ; export class Polygon extends Geometry { private _lnglats : number [ ] [ ] [ ] ; private _coordinates : number [ ] [ ] [ ] ; private _screen : number [ ] [ ] [ ] ; constructor ( lnglats ) { super ( ) ; this . _lnglats = lnglats ; } ; project ( projection ) { this . _projection = projection ; this . _coordinates = this . _lnglats . map ( ( ring ) => ring . map ( ( point ) => this . _projection . project ( point ) ) ) ; let xmin = Number . MAX_VALUE , ymin = Number . MAX_VALUE , xmax = - Number . MAX_VALUE , ymax = - Number . MAX_VALUE ; this . _coordinates . forEach ( ring => { ring . forEach ( point => { xmin = Math . min ( xmin , point [ 0 ] ) ; ymin = Math . min ( ymin , point [ 1 ] ) ; xmax = Math . max ( xmax , point [ 0 ] ) ; ymax = Math . max ( ymax , point [ 1 ] ) ; } ) ; } ) ; this . _bound = new Bound ( xmin , ymin , xmax , ymax ) ; } draw ( ctx , projection = new WebMercator ( ) , extent = projection . bound , symbol = new SimpleFillSymbol ( ) ) { if ( ! this . _projected ) this . project ( projection ) ; if ( ! extent . intersect ( this . _bound ) ) return ; const matrix = ( ctx as any ) . getTransform ( ) ; this . _screen = this . _coordinates . map ( ring => { return ring . map ( ( point , index ) => { const screenX = ( matrix . a * point [ 0 ] + matrix . e ) , screenY = ( matrix . d * point [ 1 ] + matrix . f ) ; return [ screenX , screenY ] ; } ) ; } ) ; symbol . draw ( ctx , this . _screen ) ; } getCenter ( type = CoordinateType . Latlng , projection = new WebMercator ( ) ) { if ( ! this . _projected ) this . project ( projection ) ; let i , j , p1 , p2 , f , area , x , y , center , points = this . _coordinates [ 0 ] , len = points . length ; if ( ! len ) { return null ; } area = x = y = 0 ; for ( i = 0 , j = len - 1 ; i < len ; j = i ++ ) { p1 = points [ i ] ; p2 = points [ j ] ; f = p1 [ 1 ] * p2 [ 0 ] - p2 [ 1 ] * p1 [ 0 ] ; x += ( p1 [ 0 ] + p2 [ 0 ] ) * f ; y += ( p1 [ 1 ] + p2 [ 1 ] ) * f ; area += f * 3 ; } if ( area === 0 ) { center = points [ 0 ] ; } else { center = [ x / area , y / area ] ; } if ( type === CoordinateType . Latlng ) { return projection . unproject ( center ) ; } else { return center ; } } }