以编程方式截取谷歌地图?

时间:2018-06-04 12:45:33

标签: android google-maps screenshot

我想创建一个图像。图片应包含由相机 当前地址拍摄的图片以及包含当前位置的 googlemap

enter image description here

我可以使用位置文本截取特定区域的屏幕截图并将其作为图像。 问题geting是地图区域保持空白(黑色)

我试过this但不清楚是否成功

如何在图像中实现此目的。感谢

2 个答案:

答案 0 :(得分:1)

获取Google地图图像(位图)的最简单方法 - 使用Google Maps Static API。要下载带有地图中心的lat / lng坐标地图和缩放的位图,您可以使用以下代码:

...
private FusedLocationProviderClient mFusedLocationClient;
...

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ...
    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this); 

}

...
// Somewhere, when you need map image
if (checkPermission()) {

    mFusedLocationClient.getLastLocation()
            .addOnSuccessListener(MainActivity.this, new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    if (location != null) {
                        String mapUrl = buildStaticApiUrl(new LatLng(location.getLatitude(), location.getLongitude()), zoom, mapWidthInPixels, mapHeightInPixels);

                        try {
                            Bitmap mapBitmap = new GetStaticMapAsyncTask().execute(mapUrl).get();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } catch (ExecutionException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
}

buildStaticApiUrl()可以是:

private String buildStaticApiUrl(LatLng center, int zoom, int width, int height) {

    StringBuilder url = new StringBuilder();
    url.append("http://maps.googleapis.com/maps/api/staticmap?");
    url.append(String.format("center=%8.5f,%8.5f", center.latitude, center.longitude));
    url.append(String.format("&zoom=%d", zoom));
    url.append(String.format("&size=%dx%d", width, height));
    url.append(String.format("&key=%s", getResources().getString(R.string.google_maps_key)));

    return url.toString();
}

GetStaticMapAsyncTask喜欢:

private class GetStaticMapAsyncTask extends AsyncTask<String, Void, Bitmap> {

    protected void onPreExecute() {
        super.onPreExecute();
    }

    protected Bitmap doInBackground(String... params) {

        Bitmap bitmap = null;
        HttpURLConnection connection = null;

        try {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();

            InputStream stream = connection.getInputStream();
            Bitmap mapBitmap = BitmapFactory.decodeStream(stream);

            // draw blue circle on current location
            Paint locaionMarkerPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            locaionMarkerPaint.setColor(Color.BLUE);

            bitmap = Bitmap.createBitmap(mapBitmap.getWidth(), mapBitmap.getHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            canvas.drawBitmap(mapBitmap,0,0, null);
            canvas.drawCircle(mapBitmap.getWidth()/ 2, mapBitmap.getHeight() / 2, 20, locaionMarkerPaint);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }

        return bitmap;
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        super.onPostExecute(result);

    }
} 

然后,当您同时获得pictureFromCameraBitmapmapBitmap位图时,您可以将它们组合成一个pictureBitmap

public Bitmap composeBitmap(Bitmap pictureBitmap, Bitmap mapBitmap, LatLng location) {
    Bitmap wholeBitmap = Bitmap.createBitmap(pictureBitmap.getWidth(), pictureBitmap.getHeight(), Bitmap.Config.ARGB_8888);

    Canvas canvas = new Canvas(wholeBitmap);
    canvas.drawBitmap(pictureBitmap,0,0, null);
    canvas.drawBitmap(mapBitmap,0,wholeBitmap.getHeight() - mapBitmap.getHeight(), null);

    String text = getCurrentTimeStr() + getAddress(location);
    canvas.drawText(text, 0, 0, null);

    return wholeBitmap;
}

getAddress()就像那样

public String getAddress(LatLng location) {
    StringBuilder addr = new StringBuilder();
    Geocoder geocoder = new Geocoder(this, Locale.getDefault());
    try {
        List<Address> addresses = geocoder.getFromLocation(location.latitude, location.longitude, 1);
        Address obj = addresses.get(0);
        addr.append(obj.getAddressLine(0));
    } catch (IOException e) {
    }

    return addr.toString();
}

或者,如果您不想使用Static Maps API,则可以使用基于MapView的地图快照解决方法,例如thisthat个答案:

GoogleMapOptions options = new GoogleMapOptions()
        .compassEnabled(false)
        .mapToolbarEnabled(false)
        .camera(CameraPosition.fromLatLngZoom(KYIV,15))
        .liteMode(true);
mMapView = new MapView(this, options);
...

mMapView.setDrawingCacheEnabled(true);
mMapView.measure(View.MeasureSpec.makeMeasureSpec(mMapWidth, View.MeasureSpec.EXACTLY),
        View.MeasureSpec.makeMeasureSpec(mMapHeight, View.MeasureSpec.EXACTLY));
mMapView.layout(0, 0, mMapWidth, mMapHeight);
mMapView.buildDrawingCache(true);
Bitmap b = Bitmap.createBitmap(mMapView.getDrawingCache());  // <- that is bitmap with map image
mMapView.setDrawingCacheEnabled(false);

答案 1 :(得分:0)

您可以使用查看并查找视图和绘图缓存并进行截屏。

               View v = rootView.findViewById(R.id.frmMapView);                                     v.setDrawingCacheEnabled(true);
                Bitmap backBitmap = v.getDrawingCache();
                Bitmap tripimage = Bitmap.createBitmap(
                        backBitmap.getWidth(), backBitmap.getHeight(),
                        backBitmap.getConfig());
                Canvas canvas = new Canvas(tripimage);
                canvas.drawBitmap(snapshot, new Matrix(), null);
                canvas.drawBitmap(backBitmap, 0, 0, null);

                bitmap = snapshot;

                profilePath = "/mnt/sdcard/" + "MyMapScreen" + System.currentTimeMillis() + ".png";
                FileOutputStream out = new FileOutputStream(profilePath);
                tripimage.compress(Bitmap.CompressFormat.PNG, 100, out);