001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.tools; 003 004import static org.openstreetmap.josm.tools.I18n.tr; 005 006import java.util.regex.Matcher; 007import java.util.regex.Pattern; 008 009import org.openstreetmap.josm.data.Bounds; 010 011/** 012 * Parses a Geo URL (as specified in <a href="https://tools.ietf.org/html/rfc5870">RFC 5870</a>) into {@link Bounds}. 013 * 014 * Note that Geo URLs are also handled by {@link OsmUrlToBounds}. 015 */ 016public final class GeoUrlToBounds { 017 018 /** 019 * The pattern of a geo: url, having named match groups. 020 */ 021 public static final Pattern PATTERN = Pattern.compile("geo:(?<lat>[+-]?[0-9.]+),(?<lon>[+-]?[0-9.]+)(\\?z=(?<zoom>[0-9]+))?"); 022 023 private GeoUrlToBounds() { 024 // Hide default constructor for utils classes 025 } 026 027 /** 028 * Parses a Geo URL (as specified in <a href="https://tools.ietf.org/html/rfc5870">RFC 5870</a>) into {@link Bounds}. 029 * @param url the URL to be parsed 030 * @return the parsed {@link Bounds} 031 */ 032 public static Bounds parse(final String url) { 033 CheckParameterUtil.ensureParameterNotNull(url, "url"); 034 final Matcher m = PATTERN.matcher(url); 035 if (m.matches()) { 036 final double lat; 037 final double lon; 038 final int zoom; 039 try { 040 lat = Double.parseDouble(m.group("lat")); 041 } catch (NumberFormatException e) { 042 Logging.warn(tr("URL does not contain valid {0}", tr("latitude")), e); 043 return null; 044 } 045 try { 046 lon = Double.parseDouble(m.group("lon")); 047 } catch (NumberFormatException e) { 048 Logging.warn(tr("URL does not contain valid {0}", tr("longitude")), e); 049 return null; 050 } 051 try { 052 zoom = m.group("zoom") != null ? Integer.parseInt(m.group("zoom")) : 18; 053 } catch (NumberFormatException e) { 054 Logging.warn(tr("URL does not contain valid {0}", tr("zoom")), e); 055 return null; 056 } 057 return OsmUrlToBounds.positionToBounds(lat, lon, zoom); 058 } else { 059 return null; 060 } 061 } 062}