我导入经度和纬度坐标的csv并将其转换为多边形shapefile。我在多边形上放置一个网格,然后找到每个网格正方形的质心。然后,我提取质心的坐标并将其放置在数据框中,但是我需要能够说出特定质心位于哪个多边形中。
function initMap(origins, destinations) {
let result = 0;
// var bounds = new google.maps.LatLngBounds;
var service = new google.maps.DistanceMatrixService;
var d = $.Deferred();
//calculate time here
service.getDistanceMatrix({
origins: origins,
destinations: destinations,
travelMode: 'DRIVING',
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false,
}, callback);
function callback(response, status) {
if (status !== 'OK') {
alert('Error was: ' + status);
d.reject(status);
} else {
// var originList = response.originAddresses;
// var destinationList = response.destinationAddresses;
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = '';
d.resolve(response);
var ans = response.rows[0].elements;
result = ans[0].duration;
// console.log('in callback: ')
// console.log(result.value)
}
// }); //distance matrix func
}
return d.promise();
}//initMap function
PolygonBitCentroids数据帧的前三行如下:
#Create shapefile of polygons
polygon <- lapply(split(df, df$shape), function(x) { coords <-
as.matrix(cbind(x$longitude, x$latitude)); list(rbind(coords, coords[1,]))})
Coord_Ref <- st_crs(4326)
polygon <- st_sfc(st_multipolygon(x=polygon), crs = Coord_Ref)
polygon <- st_cast(polygon, "POLYGON")
#Create grid and centroids
PolygonBits <- st_make_grid(polygon, cellsize=0.0002)
PolygonBitCentroids <- st_centroid(st_make_grid(polygon, cellsize=0.0002))
#Extract coordinates and place them in dataframe
PolygonBitCentroids <- st_coordinates(PolygonBitCentroids)
PolygonBitCentroids <- as.data.frame(PolygonBitCentroids)
但是我需要这样的东西:
X Y
1 -0.0014 0.1990
2 -0.0012 0.1990
3 -0.0010 0.1990
可复制的数据:
X Y Shape
1 -0.0014 0.1990 Polygon 1
2 -0.0012 0.1990 Polygon 1
3 -0.0010 0.1990 Polygon 1
答案 0 :(得分:0)
解决此问题的方法是通过st_join
进行多边形定位。
这对tidyverse非常简单,我确定您可以使用以下内容转换为基数R。
(我可以自由更改您的可复制数据,因为 polygon 4
不是有效的多边形,因为它只有3点):
首先,我们从xy数据框中创建一个sf
library(sf)
library(tidyverse)
polygons <- polygons %>%
st_as_sf(coords = c('longitude', 'latitude')) %>%
st_set_crs(4326)
polygons <- polygons %>%
group_by(shape) %>%
summarise(do_union=FALSE) %>%
st_cast("POLYGON")
这将正确地从这些点创建多边形。
(do_union=FALSE
参数很重要,因为否则将不保留顺序)。接下来,我们为网格创建一个单独的sf
对象:
grids <- polygons %>%
st_make_grid(cellsize = 0.2) %>%
st_centroid() %>%
st_sf()
最后,我们加入两个sf objects using
st_within`
grids %>% st_join(polygons, join = st_within)
所获得的外观完全符合您的要求。
Simple feature collection with 92 features and 1 field
geometry type: POINT
dimension: XY
bbox: xmin: -1.9 ymin: -1.9 xmax: 1.9 ymax: 1.9
CRS: EPSG:4326
First 10 features:
shape geometry
1 <NA> POINT (-1.9 -1.9)
2 <NA> POINT (-1.1 -1.9)
3 <NA> POINT (-0.9 -1.9)
4 polygon 3 POINT (-1.9 -1.7)
5 <NA> POINT (-1.7 -1.7)
6 <NA> POINT (-1.3 -1.7)
7 polygon 3 POINT (-1.1 -1.7)
8 <NA> POINT (-0.9 -1.7)
9 polygon 3 POINT (-1.9 -1.5)
10 polygon 3 POINT (-1.7 -1.5)
如果您plot
输出,您将得到