如何根据它的坐标更改矩形区域?

时间:2018-01-13 15:54:27

标签: android google-maps

我正在开发一款Android应用。我有一个多边形/矩形,它在谷歌地图上有4个边界/坐标。我有一个名为areaDifference的变量,它被设置为任意值。我需要取这个变量的值并改变矩形的大小。例如,如果areaDifference设置为2,我需要将矩形设置为两倍大。我该如何改变大小?我只有4个坐标和区域变量。

1 个答案:

答案 0 :(得分:0)

只需将多边形/矩形的LatLon坐标转换为屏幕坐标,将屏幕坐标乘以areaDifference并将其转换回LatLon。这样的事情:

Polygon polygon = mGoogleMap.addPolygon(new PolygonOptions()
.add(new LatLng(0, 0), new LatLng(0, 1), new LatLng(1, 1), new LatLng(1, 0))
.strokeColor(Color.RED)
.fillColor(Color.GREEN));

List<LatLng> points = polygon.getPoints();
List<LatLng> scaledPoints = new ArrayList(points.size());

Projection projection = mGoogleMap.getProjection();
for (int i=0; i<points.size(); i++) {
    Point screenPosition = projection.toScreenLocation(points.get(i));
    screenPosition.x = areaDifference * screenPosition.x;
    screenPosition.y = areaDifference * screenPosition.y;
    LatLng latLng = projection.fromScreenLocation(screenPosition);
    scaledPoints.add(latLng);
}
polygon.setPoints(scaledPoints);

有关缩放here的详细信息。

<强>更新

对于围绕多边形中心缩放,您应该实现更多仿射变换:将多边形/矩形的LatLon坐标转换为屏幕坐标,将多边形的中心移动到屏幕cootds(0,0),将屏幕坐标乘以{{1} },将多边形的中心移动到它的原始点并将其转换回LatLon。您可以使用比方法更多的方法:

areaDifference

用法:

private static List<LatLng> scalePolygonPoints(List<LatLng> points, float scale, Projection projection) {
    List<LatLng> scaledPoints = new ArrayList(points.size());

    LatLng polygonCenter = getPolygonCenterPoint(points);
    Point centerPoint = projection.toScreenLocation(polygonCenter);

    for (int i=0; i < points.size(); i++) {
        Point screenPosition = projection.toScreenLocation(points.get(i));
        screenPosition.x = (int) (scale * (screenPosition.x - centerPoint.x) + centerPoint.x);
        screenPosition.y = (int) (scale * (screenPosition.y - centerPoint.y) + centerPoint.y);
        LatLng latLng = projection.fromScreenLocation(screenPosition);
        scaledPoints.add(latLng);
    }

    return scaledPoints;
}

private static LatLng getPolygonCenterPoint(List<LatLng> polygonPointsList){
    LatLng centerLatLng = null;
    LatLngBounds.Builder builder = new LatLngBounds.Builder();
    for(int i = 0; i < polygonPointsList.size() ; i++) {
        builder.include(polygonPointsList.get(i));
    }
    LatLngBounds bounds = builder.build();
    centerLatLng =  bounds.getCenter();
    return centerLatLng;
}