如何在Android中的Google地图上绘制网格?

时间:2018-09-16 10:28:38

标签: java android google-maps google-api

我想创建一个类似于What3Words应用程序的网格。
What3Words
相机缩放到某个级别之后,网格就会显示出来并随着用户缩放而缩放。

我已经尝试foo并成功创建了一个网格。问题在于,网格在每次缩放时都会重绘。我希望栅格而不是重绘,以缩放级别进行缩放。

然后我转到z并使用已经绘制的网格,发现了两个问题:图像质量比原始图像差,并且像TileOverlay一样,它无法缩放缩放。

然后我尝试使用多边形绘制正方形并使用GroundOverlay提供的经度和纬度,并且由于地球是一个球体,因此网格的大小在不同区域上不一致。

现在我正在使用画布手动绘制它。

你们中的任何一个人不知道如何实现我想做的事情吗?

谢谢。

1 个答案:

答案 0 :(得分:1)

好吧,此答案演示了图形更新以绘制和移动网格,并尝试使用w3w API对齐网格。

因此使用w3w的一个问题似乎是如何计算 网格单元。由于该算法显然是私有的,因此对于此实现 “ grid” rest api调用用于当前屏幕中心点(处于空闲状态),并且json响应已解析为候选参考点。

在此示例中,始终为“参考”网格单元绘制一个多边形 是从w3w网格调用获得的。

网格视图实现使用canvas.translate调用正确对齐 并使用从参考点计算出的偏移量绘制网格。

由于使用了SphericalUtil用法将距离映射到屏幕像素,因此该方法在任何纬度下都有效。

底部录制(低质量)。

主要活动

这里,w3w网格静止调用是在摄像机闲置时进行的,并且可以进行足够远的缩放(无需继续以近距缩放进行重新对齐)和结果(附近网格单元的角点将用作 参考点)输入到网格视图。绘制一个填充的多边形来表示 参考网格单元。

在摄像机移动时,使用相同的参考点,但使用当前屏幕位置来保持适当的偏移量。

public void what3words() {

    // some initial default position
    LatLng pt = new LatLng(38.547279, -121.461019);

    mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);

    // move map to a coordinate
    CameraUpdate cu = CameraUpdateFactory.newLatLng(pt);
    mMap.moveCamera(cu);
    cu = CameraUpdateFactory.zoomTo(14);
    mMap.moveCamera(cu);

    mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
        @Override
        public void onMapClick(LatLng latLng) {
            mMap.addCircle(new CircleOptions().radius(4).strokeColor(Color.BLUE).center(latLng));
        }
    });

    // while the camera is moving just move the grid (realign on idle)
    mMap.setOnCameraMoveListener(new GoogleMap.OnCameraMoveListener() {
        @Override
        public void onCameraMove() {
            ((GridView) findViewById(R.id.grid_any)).setAlignment(
                    null, mMap.getProjection(), mMap.getProjection().getVisibleRegion());
        }
    });

    // on idle fetch the grid using the screen center point
    mMap.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() {
        @Override
        public void onCameraIdle() {
            Log.d(TAG,"idle");


            final LatLng centerOfGridCell = mMap.getCameraPosition().target;

            if (!gridSet || mMap.getCameraPosition().zoom < 10) {
                getGrid(centerOfGridCell, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d(TAG, "reqpt: " + centerOfGridCell + " volley response: " + response);
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            JSONArray jsonArray = jsonObject.getJSONArray("lines");
                            JSONObject firstList = jsonArray.getJSONObject(1);
                            JSONObject firstPt = firstList.getJSONObject("start");
                            String lat = firstPt.getString("lat");
                            String lng = firstPt.getString("lng");
                            Log.d(TAG, "lat: " + lat + " lng: " + lng);

                            LatLng alignmentPt = new LatLng(Double.parseDouble(lat), Double.parseDouble(lng));
                            Projection p = mMap.getProjection();
                            VisibleRegion vr = p.getVisibleRegion();


                            ((GridView) findViewById(R.id.grid_any)).setAlignment(alignmentPt, p, vr);

                            if (polygon != null) {
                                polygon.remove();
                            }

                            // take alignment point and draw 3 meter square polygon
                            LatLng pt1 = SphericalUtil.computeOffset(alignmentPt, 3, 90);
                            LatLng pt2 = SphericalUtil.computeOffset(pt1, 3, 180);
                            LatLng pt3 = SphericalUtil.computeOffset(pt2, 3, 270);

                            polygon = mMap.addPolygon(new PolygonOptions().add(alignmentPt,
                                    pt1, pt2, pt3, alignmentPt)
                                    .strokeColor(Color.BLUE).strokeWidth(4).fillColor(Color.BLUE));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                });

                gridSet = true;
            }


        }
    });
}


// Issue request to w3w - REMEMBER TO REPLACE **YOURKEY** ...
private void getGrid(LatLng pt, Response.Listener<String> listener) {

    // something 9 meters to east
    LatLng otherPt = SphericalUtil.computeOffset(pt, 6.0, 225);
    String bboxStr = Double.toString(pt.latitude)+","+
            Double.toString(pt.longitude)+","+
            Double.toString(otherPt.latitude)+","+
            Double.toString(otherPt.longitude);
    RequestQueue rq = Volley.newRequestQueue(this);
    String url = "https://api.what3words.com/v2/grid?bbox="+bboxStr+"&format=json&key=YOURKEY";

    Log.d(TAG,"url="+url);
    StringRequest req = new StringRequest(Request.Method.GET, url, listener, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG, "volley error: "+error);
        }
    });

    rq.add(req);
}

网格视图

网格视图扩展了View,并且在地图布局中作为地图片段的同级。

有趣的部分是:

setAlignment -这里的3米屏幕像素范围是使用 SphericalUtil类。屏幕像素尺寸代表3米长 (在提供的参考位置)(然后用于通过计算x / y偏移量对齐网格)(然后在onDraw中使用)。请注意,此操作使用“ SphericalUtil.computeOffset”实用程序自动缩放网格,以测量东3米处的点,从而计算出等效于3米的屏幕像素。

onDraw -这里的canvas转换方法用于从计算的偏移量开始(在setAlignment中)重复网格形状。

public class GridView extends View {

    private static final String TAG = GridView.class.getSimpleName();

    BitmapDrawable bm;
    Bitmap bitmap;

    GradientDrawable gd;
    int offsetX = 0;
    int offsetY = 0;
    private int width = 16;


    public GridView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }


    public void setWidth(int w) {
        width = w;
        render();
        invalidate();
    }


    private void render() {
        setShape();
        if (gd != null) {
            bitmap = drawableToBitmap(gd);
            bm = new BitmapDrawable(getResources(), bitmap);
            bm.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
            bm.setBounds(0, 0, width, width);
        }
    }

    Point startPt;
    LatLng savedAlignmentPt;


    public void setAlignment(LatLng alignmentPt, Projection p, VisibleRegion vr) {

        if (alignmentPt == null) {
            alignmentPt = savedAlignmentPt;
        }

        if (alignmentPt == null) {
            return;
        }
        // the alignment point is the a corner of a grid square "near" the center of the screen
        savedAlignmentPt = alignmentPt;

        // compute how many screen pixels are in 3 meters using alignment point
        startPt =  p.toScreenLocation(alignmentPt);
        LatLng upperRight = SphericalUtil.computeOffset(alignmentPt, 3, 90);
        Point upperRtPt = p.toScreenLocation(upperRight);

        int pixelsOf3meters = upperRtPt.x - startPt.x;

        // don't draw grid if too small
        if (pixelsOf3meters < 16) {
            return;
        }

        setWidth(pixelsOf3meters);

        // startPt is screen location of alignment point
        offsetX = (pixelsOf3meters - (startPt.x % pixelsOf3meters));
        offsetY = (pixelsOf3meters - (startPt.y % pixelsOf3meters));

        invalidate();

    }

    private void setShape() {
        int left, right, top, bottom;
        gd = new GradientDrawable();
        gd.setShape(GradientDrawable.RECTANGLE);
        gd.setSize(width, width);
        gd.setStroke(2, Color.argb(0xff, 0xcc, 0x22, 0x22));

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        Rect rect = canvas.getClipBounds();


        final int cWidth = canvas.getWidth();
        final int cHeight = canvas.getHeight();

        if (bm == null) {
            return;
        }

        final Rect bmRect = bm.getBounds();
        if (bmRect.width() <= 8 || bmRect.height() <= 8) {
            return;
        }


        final int iterX = iterations(cWidth, -offsetX, bmRect.width());
        final int iterY = iterations(cHeight, -offsetY, bmRect.height());

        canvas.translate(-offsetX, -offsetY);

        for (int x = 0; x < iterX; x++) {
            for (int y = 0; y < iterY; y++) {
                bm.draw(canvas);
                canvas.translate(.0F, bmRect.height());
            }
            canvas.translate(bmRect.width(), -bmRect.height() * iterY);
        }
    }

    private static int iterations(int total, int start, int side) {
        final int diff = total - start;
        final int base = diff / side;
        return base + (diff % side > 0 ? 1 : 0);
    }

    public static Bitmap drawableToBitmap (Drawable drawable) {
        Bitmap bitmap = null;

        if (drawable instanceof BitmapDrawable) {
            BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
            if(bitmapDrawable.getBitmap() != null) {
                return bitmapDrawable.getBitmap();
            }
        }

        if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
            bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
        } else {
            bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        }

        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);
        return bitmap;
    }
}

注意:

enter image description here enter image description here


我正在与w3w网格API进行自己的斗争。当我为返回列表中的每个点计算起点/终点之间的距离时,我得到4.24264米,因此很明显我什么也没得到。这是一种显示结果和屏幕截图的简单方法(白色=请求中使用的当前中心,其他任何颜色=列表中点对的起点-终点;终点具有黑色轮廓)。在这里也可以清楚地看到哪个点用于对齐网格。

有趣的是,一条“线”的起点确实看起来距离下一行的起点3米(比较红色起点与蓝色起点):

enter image description here

代码:

 // plot each point as a circle
 for (int i = 0; i < jsonArray.length(); i++) {
     JSONObject startPt = jsonArray.getJSONObject(i).getJSONObject("start");
     JSONObject endPt = jsonArray.getJSONObject(i).getJSONObject("end");
     LatLng start = new LatLng(Double.parseDouble(startPt.getString("lat")), Double.parseDouble(startPt.getString("lng")));
     LatLng end = new LatLng(Double.parseDouble(endPt.getString("lat")), Double.parseDouble(endPt.getString("lng")));
     int c = colors[(i % colors.length)];
     mMap.addCircle(new CircleOptions().center(start).strokeColor(c).fillColor(c).radius(1));
     mMap.addCircle(new CircleOptions().center(end).strokeColor(Color.BLACK).fillColor(c).radius(1).strokeWidth(2));

     Log.d(TAG, "d  = "+SphericalUtil.computeDistanceBetween(start,end));
 }
 mMap.addCircle(new CircleOptions().center(centerOfGridCell).strokeColor(Color.WHITE).radius(1).strokeWidth(4));