How to use mgrs - 10 common examples

To help you get started, we’ve selected a few mgrs examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github NationalSecurityAgency / qgis-latlontools-plugin / digitizer.py View on Github external
pt = geom.asPoint()
                    lat = pt.y()
                    lon = pt.x()
                elif re.search(r'POINT\(', text) is not None:
                    m = re.findall(r'POINT\(\s*([+-]?\d*\.?\d*)\s+([+-]?\d*\.?\d*)', text)
                    if len(m) != 1:
                        raise ValueError('Invalid Coordinates')
                    lon = float(m[0][0])
                    lat = float(m[0][1])
                else:
                    lat, lon = parseDMSString(text, self.inputXYOrder)
                srcCrs = epsg4326
            elif self.inputProjection == 1:
                # This is an MGRS coordinate
                text = re.sub(r'\s+', '', text)  # Remove all white space
                lat, lon = mgrs.toWgs(text)
                srcCrs = epsg4326
            elif self.inputProjection == 4:
                text = text.strip()
                coord = olc.decode(text)
                lat = coord.latitudeCenter
                lon = coord.longitudeCenter
                srcCrs = epsg4326
            elif self.inputProjection == 5:
                text = text.strip()
                pt = utmString2Crs(text, epsg4326)
                lat = pt.y()
                lon = pt.x()
                srcCrs = epsg4326
            else:  # Is either the project or custom CRS
                if re.search(r'POINT\(', text) is None:
                    coords = re.split(r'[\s,;:]+', text, 1)
github NationalSecurityAgency / qgis-latlontools-plugin / multizoom.py View on Github external
def addSingleCoord(self):
        '''Add a coordinate from the coordinate text box.'''
        parts = [x.strip() for x in self.addLineEdit.text().split(',')]
        label = ''
        data = []
        numFields = len(parts)
        try:
            if self.settings.multiZoomToProjIsMGRS():
                '''Check to see if we have an MGRS coordinate for entry'''
                lat, lon = mgrs.toWgs(re.sub(r'\s+', '', parts[0]))
                if numFields >= 2:
                    label = parts[1]
                if numFields >= 3:
                    data = parts[2:]
            elif self.settings.multiZoomToProjIsPlusCodes():
                coord = olc.decode(parts[0])
                lat = coord.latitudeCenter
                lon = coord.longitudeCenter
                if numFields >= 2:
                    label = parts[1]
                if numFields >= 3:
                    data = parts[2:]
            elif self.settings.multiZoomToProjIsUtm():
                pt = utmString2Crs(parts[0])
                lat = pt.y()
                lon = pt.x()
github NationalSecurityAgency / qgis-latlontools-plugin / field2geom.py View on Github external
if len(coords) < 2:
                            raise ValueError('Invalid Coordinates')
                        lat = float(coords[0])
                        lon = float(coords[1])
                elif field_type == 2:  # Lon (x), Lat (y)
                    if input_crs == epsg4326:
                        lat, lon = parseDMSString(attr1, 1)
                    else:
                        coords = re.split(r'[\s,;:]+', attr1, 1)
                        if len(coords) < 2:
                            raise ValueError('Invalid Coordinates')
                        lon = float(coords[0])
                        lat = float(coords[1])
                elif field_type == 3:  # MGRS
                    m = re.sub(r'\s+', '', str(attr1))  # Remove all white space
                    lat, lon = mgrs.toWgs(m)
                elif field_type == 4:  # Plus codes
                    coord = olc.decode(attr1)
                    lat = coord.latitudeCenter
                    lon = coord.longitudeCenter
                elif field_type == 5:  # Geohash
                    (lat, lon) = geohash.decode(attr1)
                    lat = float(lat)
                    lon = float(lon)
                elif field_type == 6:  # UTM
                    pt = utmString2Crs(attr1)
                    lat = pt.y()
                    lon = pt.x()

                f = QgsFeature()
                f.setAttributes(feature.attributes())
                f.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(lon, lat)))
github NationalSecurityAgency / qgis-latlontools-plugin / mgrs.py View on Github external
def _mgrsToUps(mgrs):
    """ Converts an MGRS coordinate string to UTM projection (zone, hemisphere,
    easting and northing) coordinates

    @param mgrs - MGRS coordinate string
    @returns - tuple containing UTM zone, hemisphere, easting and northing
    """
    zone, letters, easting, northing, precision = _breakMgrsString(mgrs)

    if zone != 0:
        raise MgrsException(BADLY_FORMED)

    if letters[0] >= ALPHABET['Y']:
        hemisphere = 'N'

        idx = letters[0] - 22
        ltr2LowValue = UPS_CONSTANTS[idx][1]
        ltr2HighValue = UPS_CONSTANTS[idx][2]
        ltr3HighValue = UPS_CONSTANTS[idx][3]
        falseEasting = UPS_CONSTANTS[idx][4]
        falseNorthing = UPS_CONSTANTS[idx][5]
    else:
        hemisphere = 'S'

        ltr2LowValue = UPS_CONSTANTS[letters[0]][1]
        ltr2HighValue = UPS_CONSTANTS[letters[0]][2]
        ltr3HighValue = UPS_CONSTANTS[letters[0]][3]
github NationalSecurityAgency / qgis-latlontools-plugin / mgrs.py View on Github external
    @param longitude - longitude value
    @param precision - precision level of MGRS string
    @returns - MGRS coordinate string
    """

    # To avoid precision issues, which appear when using more than
    # 6 decimal places
    latitude = round(latitude, 6)
    longitude = round(longitude, 6)

    if math.fabs(latitude) > 90:
        raise MgrsException(
            'Latitude outside of valid range (-90 to 90 degrees).')

    if (longitude < -180) or (longitude > 360):
        raise MgrsException(
            'Longitude outside of valid range (-180 to 360 degrees).')

    if (precision < 0) or (precision > MAX_PRECISION):
        raise MgrsException('The precision must be between 0 and 5 inclusive.')

    hemisphere, zone, epsg = _epsgForWgs(latitude, longitude)
    src = osr.SpatialReference()
    src.ImportFromEPSG(4326)
    dst = osr.SpatialReference()
    dst.ImportFromEPSG(epsg)
    ct = osr.CoordinateTransformation(src, dst)
    x, y, z = ct.TransformPoint(longitude, latitude)

    if (latitude < -80) or (latitude > 84):
        # Convert to UPS
        mgrs = _upsToMgrs(hemisphere, x, y, precision)
github NationalSecurityAgency / qgis-latlontools-plugin / mgrs.py View on Github external
def _mgrsToUtm(mgrs):
    """ Converts an MGRS coordinate string to UTM projection (zone, hemisphere,
    easting and northing) coordinates.

    @param mgrs - MGRS coordinate string
    @returns - tuple containing UTM zone, hemisphere, easting, northing
    """
    zone, letters, easting, northing, precision = _breakMgrsString(mgrs)
    if zone == 0:
        raise MgrsException(BADLY_FORMED)

    if letters == ALPHABET['X'] and zone in [32, 34, 36]:
        raise MgrsException(BADLY_FORMED)

    if letters[0] < ALPHABET['N']:
        hemisphere = 'S'
    else:
        hemisphere = 'N'

    ltr2LowValue, ltr2HighValue, patternOffset = _gridValues(zone)

    # Check that the second letter of the MGRS string is within the range
    # of valid second letter values. Also check that the third letter is valid
    if (letters[1] < ltr2LowValue) \
            or (letters[1] > ltr2HighValue) \
            or (letters[2] > ALPHABET['V']):
github NationalSecurityAgency / qgis-latlontools-plugin / mgrs.py View on Github external
def _epsgForWgs(latitude, longitude):
    """ Returns corresponding UTM or UPS EPSG code from WGS84 coordinates
    @param latitude - latitude value
    @param longitude - longitude value
    @returns - tuple containing hemisphere, UTM zone and EPSG code
    """

    if math.fabs(latitude) > 90:
        raise MgrsException(
            'Latitude outside of valid range (-90 to 90 degrees).')

    if longitude < -180 or longitude > 360:
        return MgrsException(
            'Longitude outside of valid range (-180 to 360 degrees).')

    # hemisphere
    if latitude < 0:
        hemisphere = 'S'
    else:
        hemisphere = 'N'

    # UTM zone
    if latitude <= -80 or latitude >= 84:
        # Coordinates falls under UPS system
        zone = 61
github NationalSecurityAgency / qgis-latlontools-plugin / mgrs.py View on Github external
def _clean_mgrs_str(s):
    """
    Clean up MGRS user-input string.
    :param s: MGRS input string
    :return: Cleaned and stripped string as Unicode
    """
    log.debug('in: {0}'.format(s))
    if str(type(s)) not in ["",
                            "",
                            "",
                            ""]:
        raise MgrsException(BADLY_FORMED)

    # convert to unicode, so str.isdigit, etc work in Py2
    if str(type(s)) == "":  # Py 3
        s = s.decode()  #  as UTF-8
    elif str(type(s)) == "":  # Py 2
        s = unicode(s, encoding='UTF-8')  # 

    # strip whitespace
    s = re.sub(r'\s+', '', s)

    # prepend 0 to input of single-digit zone
    count = sum(1 for _ in itertools.takewhile(str.isdigit, s))
    if count == 0:
        s = u'00' + s
    elif count == 1:
        s = u'0' + s
github NationalSecurityAgency / qgis-latlontools-plugin / mgrs.py View on Github external
ltr2LowValue = None
    ltr2HighValue = None

    if setNumber in [1, 4]:
        ltr2LowValue = ALPHABET['A']
        ltr2HighValue = ALPHABET['H']
    elif setNumber in [2, 5]:
        ltr2LowValue = ALPHABET['J']
        ltr2HighValue = ALPHABET['R']
    elif setNumber in [3, 6]:
        ltr2LowValue = ALPHABET['S']
        ltr2HighValue = ALPHABET['Z']

    if ltr2LowValue is None or ltr2HighValue is None:
        raise MgrsException(BADLY_FORMED)

    if setNumber % 2:
        patternOffset = 0.0
    else:
        patternOffset = 500000.0

    return ltr2LowValue, ltr2HighValue, patternOffset
github NationalSecurityAgency / qgis-latlontools-plugin / mgrs.py View on Github external
    @param hemisphere - hemisphere either 'N' or 'S'
    @param easting - easting/X in meters
    @param northing - northing/Y in meters
    @param precision - precision level of MGRS string
    @returns - MGRS coordinate string
    """
    if hemisphere not in ['N', 'S']:
        raise MgrsException('Invalid hemisphere ("N" or "S").')

    if (easting < MIN_EAST_NORTH) or (easting > MAX_EAST_NORTH):
        raise MgrsException(
            'Easting outside of valid range (100,000 to 900,000 meters '
            'for UTM, 0 to 4,000,000 meters for UPS).')

    if (northing < MIN_EAST_NORTH) or (northing > MAX_EAST_NORTH):
        raise MgrsException(
            'Northing outside of valid range (0 to 10,000,000 meters for UTM, '
            '0 to 4,000,000 meters for UPS).')

    if (precision < 0) or (precision > MAX_PRECISION):
        raise MgrsException('The precision must be between 0 and 5 inclusive.')

    letters = [None, None, None]
    if hemisphere == 'N':
        if easting >= TWOMIL:
            letters[0] = ALPHABET['Z']
        else:
            letters[0] = ALPHABET['Y']

        idx = letters[0] - 22
        ltr2LowValue = UPS_CONSTANTS[idx][1]
        falseEasting = UPS_CONSTANTS[idx][4]

mgrs

MGRS coordinate conversion for Python

MIT
Latest version published 4 months ago

Package Health Score

71 / 100
Full package analysis