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