001 // License: GPL. For details, see LICENSE file.
002 package org.openstreetmap.josm.data.imagery;
003
004 import static org.openstreetmap.josm.tools.I18n.tr;
005
006 import java.text.MessageFormat;
007 import java.util.ArrayList;
008 import java.util.List;
009
010 import org.openstreetmap.gui.jmapviewer.Coordinate;
011 import org.openstreetmap.josm.data.coor.LatLon;
012 import org.openstreetmap.josm.data.osm.Node;
013 import org.openstreetmap.josm.tools.CheckParameterUtil;
014 import org.openstreetmap.josm.tools.Geometry;
015
016 /**
017 * @author Vincent
018 *
019 */
020 public class Shape {
021
022 private List<Coordinate> coords = new ArrayList<Coordinate>();
023
024 public Shape(String asString, String separator) throws IllegalArgumentException {
025 CheckParameterUtil.ensureParameterNotNull(asString, "asString");
026 String[] components = asString.split(separator);
027 if (components.length % 2 != 0)
028 throw new IllegalArgumentException(MessageFormat.format("Even number of doubles expected in string, got {0}: {1}", components.length, asString));
029 for (int i=0; i<components.length; i+=2) {
030 addPoint(components[i], components[i+1]);
031 }
032 }
033
034 public Shape() {
035 }
036
037 public String encodeAsString(String separator) {
038 StringBuffer sb = new StringBuffer();
039 for (Coordinate c : coords) {
040 if (sb.length() != 0) {
041 sb.append(separator);
042 }
043 sb.append(c.getLat()).append(separator).append(c.getLon());
044 }
045 return sb.toString();
046 }
047
048 public List<Coordinate> getPoints() {
049 return coords;
050 }
051
052 public boolean contains(LatLon latlon) {
053 if (latlon == null)
054 return false;
055 List<Node> nodes = new ArrayList<Node>(coords.size());
056 for (Coordinate c : coords) {
057 nodes.add(new Node(new LatLon(c.getLat(), c.getLon())));
058 }
059 return Geometry.nodeInsidePolygon(new Node(latlon), nodes);
060 }
061
062 public void addPoint(String sLat, String sLon) throws IllegalArgumentException {
063 CheckParameterUtil.ensureParameterNotNull(sLat, "sLat");
064 CheckParameterUtil.ensureParameterNotNull(sLon, "sLon");
065
066 double lat, lon;
067
068 try {
069 lat = Double.parseDouble(sLat);
070 if (!LatLon.isValidLat(lat))
071 throw new IllegalArgumentException(tr("Illegal latitude value ''{0}''", lat));
072 } catch (NumberFormatException e) {
073 throw new IllegalArgumentException(MessageFormat.format("Illegal double value ''{0}''", sLat));
074 }
075
076 try {
077 lon = Double.parseDouble(sLon);
078 if (!LatLon.isValidLon(lon))
079 throw new IllegalArgumentException(tr("Illegal longitude value ''{0}''", lon));
080 } catch (NumberFormatException e) {
081 throw new IllegalArgumentException(MessageFormat.format("Illegal double value ''{0}''", sLon));
082 }
083
084 coords.add(new Coordinate(LatLon.roundToOsmPrecision(lat), LatLon.roundToOsmPrecision(lon)));
085 }
086 }