Set a max zoom level on LatLngBounds builder

前端 未结 10 639
慢半拍i
慢半拍i 2020-12-13 00:57

I haven\'t found an answer in my search, there are a few answers on SO but they didn\'t work for me.

I have 2 markers on the map and I am using LatLngBounds builder

10条回答
  •  被撕碎了的回忆
    2020-12-13 01:33

    I have a similar case, where I want at least a map diagonal of 2 kilometers. Therefore I just add two additional points to the builder: the first 1 km north-west of the center of the original bounds and the second 1 km south-east of the center. If these are inside the bounds, they do not change anything. If they are outside of the original bounds, they increase the bounds to a meaningful size.

    Here is a full code example:

    public LatLngBounds createBoundsWithMinDiagonal(MarkerOptions firstMarker, MarkerOptions secondMarker) {
        LatLngBounds.Builder builder = new LatLngBounds.Builder();
        builder.include(firstMarker.getPosition());
        builder.include(secondMarker.getPosition());
    
        LatLngBounds tmpBounds = builder.build();
        /** Add 2 points 1000m northEast and southWest of the center.
         * They increase the bounds only, if they are not already larger
         * than this. 
         * 1000m on the diagonal translates into about 709m to each direction. */
        LatLng center = tmpBounds.getCenter();
        LatLng northEast = move(center, 709, 709);
        LatLng southWest = move(center, -709, -709);
        builder.include(southWest);
        builder.include(northEast);
        return builder.build();     
    }
    
    private static final double EARTHRADIUS = 6366198;
    /**
     * Create a new LatLng which lies toNorth meters north and toEast meters
     * east of startLL
     */
    private static LatLng move(LatLng startLL, double toNorth, double toEast) {
        double lonDiff = meterToLongitude(toEast, startLL.latitude);
        double latDiff = meterToLatitude(toNorth);
        return new LatLng(startLL.latitude + latDiff, startLL.longitude
                + lonDiff);
    }
    
    private static double meterToLongitude(double meterToEast, double latitude) {
        double latArc = Math.toRadians(latitude);
        double radius = Math.cos(latArc) * EARTHRADIUS;
        double rad = meterToEast / radius;
        return Math.toDegrees(rad);
    }
    
    
    private static double meterToLatitude(double meterToNorth) {
        double rad = meterToNorth / EARTHRADIUS;
        return Math.toDegrees(rad);
    }
    

提交回复
热议问题