提取多边形质心的坐标并用多边形编号标记它们

问题描述

我导入经度和纬度坐标的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

解决方法

解决此问题的方法是通过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) 

绘制时,看起来像这样 the points

polygons <- polygons %>%
  group_by(shape) %>%
  summarise(do_union=FALSE) %>%
  st_cast("POLYGON")

这将正确地从这些点创建多边形。

plot(polygons)的调用产生以下图: the polygons

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输出,您将得到

grouped grid centroids

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...