Thursday, 7 March 2013

Set zoomlevels for gwt-openlayers and openstreetmap

I tried to make the zoom level bar show the same number of zoom levels as my offline cache and I'm shocked at how little information is out there about this.

The method below is doing the trick for me now:

/**
     * @param options
     * @param minZoomLevel the minimum for this is 3 for open streetmap
     * @param maxZoomLevel
     */
    private static void setZoomLevelRange(LayerOptions options,
        int minZoomLevel, int maxZoomLevel) {
        options.getJSObject().setProperty("zoomOffset", minZoomLevel);

        int len = maxZoomLevel - minZoomLevel + 1;
        double[] resolutions = new double[len];
        double curRes = 78271.51695 / (Math.pow(2, minZoomLevel - 1));
        for (int i = 0; i < len; i++) {
            resolutions[i] = curRes;
            curRes = curRes / 2;
        }

        options.setResolutions(resolutions);
    }


// usage example:
        OSMOptions osmOptions = new OSMOptions();
      
        setZoomLevelRange(osmOptions, 5, 11);
      
        OSM baseTileLayer = new OSM("Mapnik", 
          // for offline tiles:
          GWT.getHostPageBaseURL()
            + "tiles/${z}/${x}/${y}.png", 
          osmOptions);



The keys are:

  1. there is apparently a magic zoom level 1 resolution (I have not found how it is calculated).
  2. you can add higher and lower resolutions by multiplying or dividing them by 2.
  3. it is critical that you set the zoomOffset in accordance to what you use as your  minimum zoom level.

Your welcome and yeah you may copy the code as you want.

References:



2 comments:

  1. Can you log a feature request with gwt-openlayers, using it a lot these days :)

    So new OSMOptions().setNumZoomLevels(x) does not work properly with OSM ?

    ReplyDelete
  2. I think setNumZoomLevels does work, it just does not let you set at what zoom level you start at :(

    ReplyDelete