# Calculating distance between geographical centroids and points?

I have one zone system and two layers. The 1st layer is the geographical centroids of the zone system (each zone has 1 geographical centroid), while the 2nd layer displays the rail stations. I would like to calculate and display the distance between the centroids and the rail stations. Ideally, I want each station to be connected to the centroid of the zone that it belongs (see pic attached). In essence, it is the shortest distance, but in some cases, one rail station might be closer to a geographical centroid of another zone and QGIS will give me this distance, which I don't want. In addition, one zone might have more than 1 rail stations. In that case, I want only the shortest distance.

Any idea on how to perform this task?

## 1 Answer

You will need to code this function down yourself. If coordinates for both centroid (cX,cY) and station (sX,sY) are known - you may use following function to compute 2D distance between two points:

`````` Math.Sqrt((sX - cX) ^ 2 + (sY - cY) ^ 2)
``````

If you are new to coding, I suggest you use Python language for this (please see QGIS - Getting Started With Python Programming).