The coordinates of the Eiffel Tower are (Longitude: 48.8584° N, Latitude: 2.2945° E). I am interested in randomly generating 100 points that are located within a 12 KM radius of the Eiffel Tower. In other words, I would like to randomly generate 100 pairs of (Longitude, Latitude) that are located within a 12 KM radius of the Eiffel Tower.
According to this question here (Simple calculations for working with lat/lon and km distance?), the following formulas can be used to convert Longitude and Latitude to KM:
Thus, if I want to find out a 12 KM radius, the corresponding maximum ranges should be:
Using this information, I tried to simulate points and plot them:
# for some reason, you have to call "long" as "lat" and vice versa - otherwise the points appear in the wrong locations all together
id = 1:100
long = 2.2945 + rnorm( 100, 0.1085246 , 1)
lat = 48.8584 + rnorm( 100, 0.009036273 , 1)
my_data = data.frame(id, lat, long)
library(leaflet)
my_data %>%
leaflet() %>%
addTiles() %>%
addMarkers(clusterOption=markerClusterOptions())
But these points do not appear near the Eiffel Tower - some of them are even in Belgium! :
I reduced the variance and now the points appear closer:
# reduce variance
id = 1:100
long = 2.2945 + rnorm( 100, 0.1085246 , 0.01)
lat = 48.8584 + rnorm( 100, 0.009036273 , 0.01)
my_data = data.frame(id, lat, long)
library(leaflet)
my_data %>%
leaflet() %>%
addTiles() %>%
addMarkers(clusterOption=markerClusterOptions())
But this of course required some guess work and playing around - ideally, I would like a more "mathematical approach".
One option is to use the sf
package. The function st_buffer
will allow you to create a 12 km circle around your starting point, and st_sample
will allow you to take 100 random points within that circle.
Create the data
library(sf)
library(dplyr)
pt_sf <- data.frame(long = 2.2945, lat = 48.8584) %>%
st_as_sf(coords = c("long", "lat"), crs = 4326)
buff <- pt_sf %>%
st_buffer(dist = units::as_units(12, 'km'))
buff_sample <- st_sample(buff, 100)
Plot it
library(leaflet)
leaflet(pt_sf) %>%
addTiles() %>%
addCircleMarkers(color = 'red') %>%
addPolygons(data = buff) %>%
addMarkers(data = buff_sample, clusterOption=markerClusterOptions())