如何在R Studio中使用gmap distance包计算恒定速度移动物体在指定时间后的经纬度位置?
Great question! Let’s break this down clearly—first, confirming R Studio has the right tools for this spatial calculation, then walking through a step-by-step example using the gmapsdistance package for your specific scenario.
Does R Studio have functions for this?
Absolutely. R has a robust ecosystem of geospatial packages that handle interpolating an object's position along a route over time. Beyond gmapsdistance, packages like sf, geosphere, and googleway are go-to tools for this kind of work. Since you’re already using gmapsdistance, we’ll focus on that plus a couple of helper packages to get the job done.
Step-by-Step Example: Position After 5 Minutes at Constant Speed
Let’s say you have an object moving from point A to point B at a constant speed, and you want its latitude/longitude after 5 minutes. Here’s how to do it:
1. Set Up Packages & Basic Parameters
First, install and load the necessary packages. We’ll use gmapsdistance to fetch route data, googleway to decode the route’s encoded polyline, and geosphere to calculate distances between points.
# Install packages if you haven't already install.packages(c("gmapsdistance", "googleway", "geosphere")) # Load packages library(gmapsdistance) library(googleway) library(geosphere)
Define your starting point (A), destination (B), speed, and target time. For this example, we’ll use two points in New York City:
# Point A (lat, lon): Manhattan point_a <- c(40.7128, -74.0060) # Point B (lat, lon): Brooklyn point_b <- c(40.7306, -73.9352) # Speed in km/h speed_kmh <- 30 # Time elapsed: 5 minutes time_elapsed_min <- 5
2. Fetch Route Data from Google Maps
Use getDirections() to get the route details, including the encoded polyline that represents the actual path. Note: You’ll need a Google Maps API key (you can get one from the Google Cloud Console) for this step.
# Replace with your Google Maps API key api_key <- "YOUR_API_KEY_HERE" # Get route directions (mode can be "driving", "walking", "bicycling", etc.) route <- gmapsdistance::getDirections( origin = paste(point_a[1], point_a[2], sep = ","), destination = paste(point_b[1], point_b[2], sep = ","), mode = "driving", key = api_key )
3. Decode the Polyline into Coordinate Points
The route’s path is stored as an encoded string in route$routes$overview_polyline$points. We’ll decode this into a data frame of latitude/longitude pairs using googleway::decode_pl():
# Decode the polyline to get all points along the route route_points <- googleway::decode_pl(route$routes$overview_polyline$points) route_df <- as.data.frame(route_points)
4. Calculate Cumulative Distance Along the Route
Next, compute the distance between each consecutive pair of points (in meters) and build a cumulative distance column. This tells us how far along the route each point is from the start:
# Calculate distance between each pair of consecutive points segment_distances <- c(0, geosphere::distHaversine(route_df[-nrow(route_df), ], route_df[-1, ])) # Add cumulative distance (in meters) to the data frame route_df$cumulative_dist_m <- cumsum(segment_distances)
5. Compute How Far the Object Has Traveled
Convert the elapsed time to hours, then calculate the total distance traveled at the given speed (convert to meters to match our cumulative distance units):
# Time elapsed in hours time_elapsed_h <- time_elapsed_min / 60 # Total distance traveled (convert km to meters) distance_traveled_m <- speed_kmh * time_elapsed_h * 1000
6. Interpolate to Find the Exact Position
Now find where along the route the object reaches after traveling distance_traveled_m. We’ll interpolate between the two points that bracket this distance to get the exact coordinates:
# Find the first point where cumulative distance exceeds our target distance idx <- which(route_df$cumulative_dist_m >= distance_traveled_m)[1] # Handle edge cases (object hasn't moved past the first point) if (is.na(idx) || idx == 1) { final_pos <- route_df[1, c("lat", "lon")] } else { # Get the two points around our target distance point_before <- route_df[idx - 1, ] point_after <- route_df[idx, ] # Calculate what fraction of the segment we've traveled segment_fraction <- (distance_traveled_m - point_before$cumulative_dist_m) / (point_after$cumulative_dist_m - point_before$cumulative_dist_m) # Interpolate latitude and longitude final_lat <- point_before$lat + segment_fraction * (point_after$lat - point_before$lat) final_lon <- point_before$lon + segment_fraction * (point_after$lon - point_before$lon) final_pos <- data.frame(lat = final_lat, lon = final_lon) } # Print the result cat(sprintf("Position after %d minutes:\n", time_elapsed_min)) print(final_pos)
Key Notes
- API Limits: Google Maps API has usage limits, so keep an eye on your quota if you’re running this frequently.
- Route Mode: The
modeparameter ingetDirections()changes the route path (driving vs walking), so pick the one that matches your object’s movement. - Interpolation: We used linear interpolation here, which works well for short segments. For very long routes, you might want to use more advanced spatial interpolation methods, but this is a reliable starting point.
内容的提问来源于stack exchange,提问作者Z.S.CS

