Search code examples
rleafletmarkers

Find the middle point between two markers in Leaflet


I would like to be able to find the centre point between two markers on a map (example below). Is there a function in leaflet or in another package that allows this? Thank you in advance

coor_zone6 <- c(3.16680, 3.16176, 42.46667, 42.46997)
matrice_coord_zone6 <- matrix(coor_zone6, nrow=2, ncol = 2)
colnames(matrice_coord_zone6) <- c("long", "lat")
matrice_coord_zone6 <- data.frame(matrice_coord_zone6)
matrice_coord_zone6$name <- c("M_1","M_3")

leaflet(matrice_coord_zone6) %>%
  addMouseCoordinates(epsg = NULL, proj4string = NULL, native.crs = FALSE) %>%
  addProviderTiles("Esri.WorldImagery") %>%
  addMarkers(lng = ~long, lat = ~lat) %>%
  addPolylines(~long, ~lat, popup = ~name)

Solution

  • I have not found any leaflet function that can perform this calculation, but it is not difficult to find the intermediate point between both coordinates.

    You must add both longitudes and divide them by 2, you will have to do the same with both latitudes.

    In your case, if I have not misunderstood, your first coordinate is (3.16680, 42.46667) and your second coordinate is (3.16176, 42.46997) so the calculation would be as follows:

    (3,16680 + 3,16176) / 2 = 3,16428
    (42,46667 + 42,46997) / 2 = 42,46832

    So the intermediate point would be the following: (3.16428, 42.46832)