Home > Back-end >  Converting geographical coordinates to Mercator projection grid coordinates
Converting geographical coordinates to Mercator projection grid coordinates

Time:11-11

I have to convert 4 points:

1: 0°00'00.0"S 30°00'00.0"E
2: 0°00'00.0"S 60°00'00.0"E
3: 30°00'00.0"S 60°00'00.0"E
4: 30°00'00.0"S 30°00'00.0"E

from the geographical coordinate format to a Mercator projection grid coordinates. I must do this using Python, by importing the text file containing the coordinate information of each point, converting this to decimal degrees and then radians before using this information in the following formula:

formula

to calculate the new projected coordinates. Once the calculations are complete python needs to write the Mercator projection coordinates out to a new text file.

I have managed to compute the formulas directly into Python, however I am stuck on how to read the 4 points from text file, compute the calculations, and write the new coordinates to another text file.

CodePudding user response:

You can use the regular expression re module to parse the strings.

import math
import re

datafile_path = 'geo_coords.txt'
pattern = re.compile(r"""(\d )°(\d )'([\d.] )"([NS])\s(\d )°(\d )'([\d.] )"([EW])""")

with open(datafile_path, encoding='utf8') as file:
    for line in file:
        m = pattern.search(line)
        if m:
            groups = m.groups()
            degrees, minutes, seconds = map(float, groups[:3])
            compass1 = groups[3]
            latitude = degrees   minutes/60.0   seconds/3600.0
            radians1 = math.radians(latitude)

            degrees, minutes, seconds = map(float, groups[4:7])
            compass2 = groups[7]
            longitude = degrees   minutes/60.0   seconds/3600.0
            radians2 = math.radians(longitude)

            print(f'{line}', end='')
            print(f'latitude: {latitude} {compass2} -> radians {radians1:.4f}')
            print(f'longitude: {longitude} {compass2} -> radians {radians2:.4f}')

Depending on what you're doing with the values, you may need to flip the sign based on the compass direction along these lines:

if compass1 == 'S':
    latitude = -latitude
if compass2 == 'W':
    longitude = -longitude

CodePudding user response:

You may use a regex like this one

(\d ).(\d{2}).(\d{2}.\d).([SNWE])

to have your coordinates split in the various parts (as strings).

Then cast your values to numbers, convert to decimal degrees (d m/60 s/3600) and finally use math.radians()

  • Related