javaswingvalidationgpscoordinates

How to validate geographic coordinates?


I'm trying to validate the text of a JTextField. The content of this textfield should be something like this 66.160507, -153.369141 or 66.160507,-153.369141 (without whitespace after the comma). So far I validate only the range for both latitude and longitude. Here:

 String [] splitted = jtextField.getText().split(",");
 double latitude = Double.parseDouble(splitted[0]);
 double longitude = Double.parseDouble(splitted[1])

if(latitude < -90 || latitude > 90)
  return false;
else
  continue;

if(longitude < -180 || longitude > 180)
      return false;
    else
      continue;

but now how can I check whether the text in the JTextField is in the right format and order? I need to validate these two cases:

must be a double -> must be a comma -> must be a whitespace -> must be a double 
must be a double -> must be a comma -> must be a double 

Solution

  • One option would be to use a regular expression to validate the form of what's in your text field. You can read up on the different symbols you can use in a regular expression at the Javadoc for the Pattern class, but some of the ones you might use would be

    Putting this all together you might come up with a regular expression like this.

    -?[1-9][0-9]*(\.[0-9]+)?,\s*-?[1-9][0-9]*(\.[0-9]+)?
    

    to match a pair of latitude and longitude.

    This matches

    You could then write code like this.

    String textValue = jtextField.getText();
    String twoDoublesRegularExpression = "-?[1-9][0-9]*(\\.[0-9]+)?,\\s*-?[1-9][0-9]*(\\.[0-9]+)?";
    
    if (textValue.matches(twoDoublesRegularExpression)) {
        // this value is OK
    }