NativeScript / plugins

@nativescript plugins to help with your developments.
https://docs.nativescript.org/plugins/index.html
Apache License 2.0
190 stars 108 forks source link

@google-maps Offline map? #268

Open liamcharmer opened 2 years ago

liamcharmer commented 2 years ago

Anyway of allowing for maps to work offline? Or to cache or anything like that?

jamescodesthings commented 2 years ago

Yeah dude, snapshotting is fairly easy, you can screenshot the MapView, and there's a snapshot() function on GoogleMap/GoogleMapView.

The snapshot function is sometimes not brilliant.

In my app we have a MapView in the background (low z-index and above everything else in the HTML). Then I pass it into this function:

/**
 * Screenshots a view and returns its source
 * @param view The View to screenshot
 * @return an ImageSource of the thing
 */
export async function screenshotView(view: View): Promise<ImageSource> {
  if (isIOS) {
    UIGraphicsBeginImageContextWithOptions(view.ios.frame.size, false, 0);
    view.ios.drawViewHierarchyInRectAfterScreenUpdates(
      CGRectMake(0, 0, view.ios.frame.size.width, view.ios.frame.size.height),
      true,
    );
    const imageFromCurrentImageContext = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return ImageSource.fromData(UIImagePNGRepresentation(imageFromCurrentImageContext));
  }
  if (isAndroid) {
    view.nativeView.setDrawingCacheEnabled(true);
    const bmp = android.graphics.Bitmap.createBitmap(view.nativeView.getDrawingCache());
    view.nativeView.setDrawingCacheEnabled(false);
    const source = new ImageSource();
    source.setNativeSource(bmp);
    return source;
  }
  return null;
}

And finally save the image somewhere known and hot-swap the image out when connectivity is offline.

Can provide a better demo once I've fixed it.

jamescodesthings commented 2 years ago

To update on my previous comment: the snapshot() method seems more stable now.

The basic process is:

herefishyfish commented 2 years ago

Just adding to this. Google maps automatically caches XYZ tiles for offline use.