# How to convert longitudes and latitudes into mercator coordinates using python ?

Published: February 10, 2024

Tags: Python;

## Introduction

The Mercator projection is a cylindrical map projection that is commonly used because it represents lines of constant course as straight segments. However, it distorts the size and shape of large objects.

In this article, we will delve into various methods of converting longitudes and latitudes into Mercator coordinates using Python.

## Converting longitudes and latitudes into Mercator projection using geopandas

Geopandas is an open-source Python library that combines the capabilities of the powerful geospatial libraries - Shapely and PyProj - into a single package. It allows users to easily read, write, manipulate, and visualize geospatial data. Geopandas also supports various map projections, making it the ideal tool for transforming longitudes and latitudes into Mercator projections.

Let's explore the following longitudes and latitudes of various cities that we aim to convert into Mercator projection:

````data = {'city_name':['Paris','London','Moscow', 'Istanbul'],`
`       'longitude':[2.3522,-0.1276,37.6173,28.9784],`
`       'latitude':[48.8566,51.5072,55.7558,41.0082]}`
```

### Creating a geopandas dataframe

Now, we can move forward and store our data in a pandas dataframe:

````import pandas as pd`

`df = pd.DataFrame(data)`
```

Finally, we can convert our DataFrame into a Geodataframe.

````import geopandas`

`gdf = geopandas.GeoDataFrame(`
`    df, `
`    geometry=geopandas.points_from_xy(df.longitude, df.latitude), `
`    crs="EPSG:4326"`
`)`
```

Note: to determine the coordinate system CRS associated with our dataframe, we can execute the following command:

````print( gdf.crs )`
```

The code presented here does not correspond to Mercantor:

````EPSG:4326`
```

### Converting longitudes and latitudes into Mercator projection using geopandas to_crs()

In order to convert our geopandas into the Mercator-projection we can do:

````gdf = gdf.to_crs("epsg:3857") # Mercator-projection`
```

At last, our dataset has transformed into the following format:

````  city_name  longitude  latitude                         geometry`
`0     Paris     2.3522   48.8566   POINT (261845.706 6250564.350)`
`1    London    -0.1276   51.5072   POINT (-14204.367 6711506.705)`
`2    Moscow    37.6173   55.7558  POINT (4187538.681 7509955.142)`
`3  Istanbul    28.9784   41.0082  POINT (3225860.732 5013551.237)`
```

### Extracting Mercator projection coordinates from the geopandas dataframe

In the final step, we will extract the coordinates in the Mercator projection that correspond to the given longitudes and latitudes

````gdf['longitude_x'] = gdf['geometry'].x`
`gdf['latitude_y'] = gdf['geometry'].y`
```

Now, the geodataframe has two new columns that will be used to plot our points:

````  city_name  longitude  latitude                         geometry  \`
`0     Paris     2.3522   48.8566   POINT (261845.706 6250564.350)   `
`1    London    -0.1276   51.5072   POINT (-14204.367 6711506.705)   `
`2    Moscow    37.6173   55.7558  POINT (4187538.681 7509955.142)   `
`3  Istanbul    28.9784   41.0082  POINT (3225860.732 5013551.237)`

`    longitude_x    latitude_y  `
`0  2.618457e+05  6.250564e+06  `
`1 -1.420437e+04  6.711507e+06  `
`2  4.187539e+06  7.509955e+06  `
`3  3.225861e+06  5.013551e+06`
```

## Creating a custom Python function to transform longitudes and latitudes into Mercator coordinates

The most commonly used method for projecting geographical data onto a flat surface is the Spherical Mercator Projection. This projection is used by many online mapping tools, including Google Maps and OpenStreetMap. To convert latitude and longitude coordinates to Mercator coordinates using this method, the following formulas can be applied:

````Formula for X coordinate: x = R * (λ - λ0)`
`Formula for Y coordinate: y = R * ln(tan(π/4 + φ/2))`
```

In these formulas, R represents the radius of the Earth, λ is longitude in radians, λ0 is a reference longitude (typically 0), and φ is latitude in radians. The result of these formulas will be in meters.

Here's an example of how to create a Python script that converts latitude and longitude coordinates into the Mercator projection:

````import numpy as np`

`def convert_to_mercator(lats, lons):`
`    R = 6378137.000`
`    x = R * np.radians(lons)`
`    scale = x/lons`
`    y = 180.0/np.pi * np.log(np.tan(np.pi/4.0 + lats * (np.pi/180.0)/2.0)) * scale`
`    return (x, y)`
```

To organize our data, we can store the longitude and latitude values in separate arrays:

````data = {'city_name':['Paris','London','Moscow', 'Istanbul'],`
`       'longitude':[2.3522,-0.1276,37.6173,28.9784],`
`       'latitude':[48.8566,51.5072,55.7558,41.0082]}`

`lats = np.array( data['latitude'] )`
`lons = np.array( data['longitude'] )`
```

Upon applying our function

````xs, ys = convert_to_mercator(lats, lons)`

`print(xs)`
`print(ys)`
```

, the resulting output is as follows

````[ 261845.70624394  -14204.36702522 4187538.68101781 3225860.7320038 ]`
`[6250564.34954313 6711506.70540052 7509955.1423381  5013551.2372226 ]`
```

Please note that we achieve identical results using geopandas.