Search code examples
sqlopenlayerspostal-code

How to set the initial map area in OpenLayers?


I'm using Patrick Wied's OpenLayers Heatmap layer, but only for locations in the UK.

How can I preset the initial map display area to show just the UK?

Here's the code I've used in an ASPX page

  var map, layer, heatmap;
  function init() {
    var testData = <asp:literal id="cLtMapData" runat="server" />    
    var transformedTestData = { max: testData.max, data: [] },
        data = testData.data,
        datalen = data.length,
        nudata = [];
    // in order to use the OpenLayers Heatmap Layer we have to transform our data into
    // { max: <max>, data: [{lonlat: <OpenLayers.LonLat>, count: <count>},...]}
    while (datalen--) {
      nudata.push({
        lonlat: new OpenLayers.LonLat(data[datalen].lon, data[datalen].lat),
        count: data[datalen].count
      });
    }
    transformedTestData.data = nudata;
    map = new OpenLayers.Map('heatmapArea');
    layer = new OpenLayers.Layer.OSM();

    // create our heatmap layer
    heatmap = new OpenLayers.Layer.Heatmap("Heatmap Layer", map, layer, { visible: true, radius: 10 }, { isBaseLayer: false, opacity: 0.3, projection: new OpenLayers.Projection("EPSG:4326") });
    map.addLayers([layer, heatmap]);
    map.zoomToMaxExtent();
    //maxExtent: new OpenLayers.Bounds(-1*b, -1*b, b, b);
    map.zoomIn();
    heatmap.setDataSet(transformedTestData);
  }

It's almost exactly like Patrick's demo pages, but with one difference - var testData = (an asp literal) - so that I can use dynamic data selected bu the user, and retrieved from an SQL Database via a stored procedure that translates UK postcodes into latitude and longitude.


Solution

  • I would do it in the map initialization. Something like this:

    map = new OpenLayers.Map({
            projection: new OpenLayers.Projection("EPSG:900913"),
            units: "m",
            numZoomLevels: 18,
            maxResolution: 156543.0339,
            maxExtent: new OpenLayers.Bounds(
                -20037508.34, -20037508.34, 20037508.34, 20037508.34
            ),
            layers: [
                new OpenLayers.Layer.OSM("OpenStreetMap", null, {
                    transitionEffect: 'resize'
                })
            ],
            center: new OpenLayers.LonLat(-10309900, 4215100),
            zoom: 4
        });