2

I'm trying to display an OpenLayers 3 map in an Android WebView. Only the zoom controls and the copyright hint are displayed, the map itself not. JavaScript is enabled for the WebView, right to access the internet is granted. I tested on a Nexus 5 with Android 7 (API 24).

If I load exactly the same JavaScript code in Chrome on Android, the map is displayed fine.

In the meantime I managed to display the map but I'm not happy about this solution, as the map is pretty blurry. It works only, if I set "pixelRatio:1" and call map.setSize and pass the half of width/height of the container div. If I pass just the full width/height, nothing is displayed. Here is my code:

<html>
<head>
   <meta charset="utf8" />
   <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
   <script src="ol.js"></script>
   <link rel="stylesheet" href="ol.css" type="text/css">
</head>
<body style="margin: 0; padding: 0;">
   <div id="map" class="map"></div>

   <script type="text/javascript">
   var view = new ol.View(
   {
      center: [0, 0],
      zoom: 2
   });

   var map = new ol.Map(
   {
      layers: [
         new ol.layer.Tile(
         {
            source: new ol.source.OSM()
         })
      ],
      target: 'map',
      controls: ol.control.defaults(
      {
         attributionOptions: (
         {
            collapsible: false
         })
      }),
      view: view,
      pixelRatio: 1
   });

   var mapDiv = document.getElementById("map");
   map.setSize([mapDiv.offsetWidth/2, mapDiv.offsetHeight/2]);
   </script>
</body>
</html>

On Android I use these settings for the WebView:

mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setAllowFileAccessFromFileURLs(true);
mWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);

[Update] I just loaded several example maps from here http://openlayers.org/en/v3.2.1/examples/ into my WebView. Not a single map was displayed. Additionally I loaded some of the examples in the official Android WebView Browser Tester with exactly the same result. So now I'm sure that it's not a problem of my specific map or WebView but a general problem displaying OpenLayers maps on an Android WebView.

[Update 2] I switched now to leaflet where the map is displayed without problems. Additionally leaflet seems to me much easier to use.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.