001/**
002 * Copyright (c) 2011, The University of Southampton and the individual contributors.
003 * All rights reserved.
004 *
005 * Redistribution and use in source and binary forms, with or without modification,
006 * are permitted provided that the following conditions are met:
007 *
008 *   *  Redistributions of source code must retain the above copyright notice,
009 *      this list of conditions and the following disclaimer.
010 *
011 *   *  Redistributions in binary form must reproduce the above copyright notice,
012 *      this list of conditions and the following disclaimer in the documentation
013 *      and/or other materials provided with the distribution.
014 *
015 *   *  Neither the name of the University of Southampton nor the names of its
016 *      contributors may be used to endorse or promote products derived from this
017 *      software without specific prior written permission.
018 *
019 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
020 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
021 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
022 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
023 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
024 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
025 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
026 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
027 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
028 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
029 */
030package org.openimaj.text.geo;
031
032import java.util.ArrayList;
033import java.util.Collection;
034import java.util.HashMap;
035import java.util.List;
036import java.util.Map;
037
038import javax.xml.parsers.DocumentBuilder;
039import javax.xml.parsers.DocumentBuilderFactory;
040
041import org.openimaj.math.geometry.point.Point2d;
042import org.openimaj.math.geometry.point.Point2dImpl;
043import org.openimaj.math.geometry.shape.Polygon;
044import org.openimaj.math.geometry.shape.Rectangle;
045import org.openimaj.math.geometry.shape.Shape;
046import org.w3c.dom.Document;
047import org.w3c.dom.Element;
048import org.w3c.dom.Node;
049import org.w3c.dom.NodeList;
050
051/**
052 * @author Sina Samangooei (ss@ecs.soton.ac.uk)
053 *
054 */
055public class WorldPolygons {
056        private static Document doc;
057        static {
058                final DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
059
060                try {
061                        final DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
062                        doc = dBuilder.parse(WorldPolygons.class.getResourceAsStream("countries_world.kml"));
063
064                } catch (final Exception e) {
065                        throw new RuntimeException();
066                }
067        }
068
069        private Map<String, WorldPlace> countryShapes;
070        private Map<String, WorldPlace> countryCodeShapes;
071        private Rectangle bounds;
072
073        public WorldPolygons() {
074                this.countryShapes = new HashMap<String, WorldPlace>();
075                countryCodeShapes = new HashMap<String, WorldPlace>();
076                doc.getDocumentElement().normalize();
077                final NodeList places = doc.getElementsByTagName("Placemark");
078                float minx = Integer.MAX_VALUE, miny = Integer.MAX_VALUE, maxx = -Integer.MAX_VALUE, maxy = -Integer.MAX_VALUE;
079                for (int i = 0; i < places.getLength(); i++) {
080                        final Node placeNode = places.item(i);
081                        /**
082                         * [name: null] [description: null] [LookAt: null] [Style: null]
083                         * [MultiGeometry: null]
084                         */
085                        final String name = getNodeValue(placeNode, "name");
086                        final String desc = getNodeValue(placeNode, "description");
087                        final String countryCode = desc.split(":")[0].split("=")[1].trim().toLowerCase();
088                        final Node lookat = getFirstNode(placeNode, "LookAt");
089                        final String latStr = getNodeValue(lookat, "latitude");
090                        final String lonStr = getNodeValue(lookat, "longitude");
091                        final Element multiGeom = (Element) getFirstNode(placeNode, "MultiGeometry");
092                        final NodeList polygonNodes = multiGeom.getElementsByTagName("Polygon");
093                        final List<Shape> polygons = new ArrayList<Shape>();
094                        for (int j = 0; j < polygonNodes.getLength(); j++) {
095                                final String[] coords = getNodeValue(polygonNodes.item(j), "coordinates").split(" ");
096                                final List<Point2d> points = new ArrayList<Point2d>();
097                                for (final String coord : coords) {
098                                        final String[] xy = coord.split(",");
099                                        final float fx = Float.parseFloat(xy[0]);
100                                        final float fy = Float.parseFloat(xy[1]);
101                                        minx = Math.min(minx, fx);
102                                        miny = Math.min(miny, fy);
103                                        maxx = Math.max(maxx, fx);
104                                        maxy = Math.max(maxy, fy);
105                                        points.add(new Point2dImpl(fx, fy));
106                                }
107                                polygons.add(new Polygon(points));
108                        }
109
110                        final WorldPlace place = new WorldPlace(
111                                        name, countryCode,
112                                        Float.parseFloat(latStr), Float.parseFloat(lonStr),
113                                        polygons);
114                        this.countryShapes.put(name, place);
115                        this.countryCodeShapes.put(countryCode, place);
116                }
117                this.bounds = new Rectangle(minx, miny, maxx - minx, maxy - miny);
118        }
119
120        private String getNodeValue(Node node, String nodeName) {
121                final Node firstNode = getFirstNode(node, nodeName);
122                return firstNode.getFirstChild().getNodeValue();
123        }
124
125        private Node getFirstNode(Node node, String nodeName) {
126                return ((Element) node).getElementsByTagName(nodeName).item(0);
127        }
128
129        public Collection<WorldPlace> getShapes() {
130                return this.countryShapes.values();
131        }
132
133        public WorldPlace byCountryCode(String countryCode) {
134                return this.countryCodeShapes.get(countryCode.toLowerCase());
135        }
136
137        public WorldPlace byCountry(String country) {
138                return this.countryShapes.get(country);
139        }
140
141        public Rectangle getBounds() {
142                return bounds;
143        }
144}