Chris
Chris

Reputation: 677

URL parameters for Openlayers 3 to zoom to location?

I have an OL3 web application and I am wondering if it is possible to include URL parameters (such as coordinate values) for which the application can parse and open up at a specific location?

For example http://mywebsiteaddress?x=longitudevalue&y=latitudevalue

Is this something that can be done using OL3?

Upvotes: 1

Views: 1628

Answers (2)

Andre Joost
Andre Joost

Reputation: 146

I did not like the openlayers permalink example because it uses map units and not well-known latitudes and longitudes. Sp I wrote my own code to hand over latlon coordinates, zoom and set a marker to it:

function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}

var mzoom=12;
var mlat = Number(getURLParameter('mlat'));
var mlon = Number(getURLParameter('mlon'));
var mzoom = Number(getURLParameter('zoom'));
var marker = 1
if (mlat == 0 || mlon == 0) {
      mlat = 51.5; mlon = 7.0; mzoom=12; marker=0 //Default location
  }
if (mzoom == 0 ) { mzoom=12 //Default zoom
  }   

var container = document.getElementById('popup');
var content = document.getElementById('popup-content');
var closer = document.getElementById('popup-closer');
closer.onclick = function() {
container.style.display = 'none';
closer.blur();
return false;
};
var overlayPopup = new ol.Overlay({
element: container
});

var expandedAttribution = new ol.control.Attribution({
collapsible: false
});



var map = new ol.Map({
controls: ol.control.defaults({attribution:false}).extend([
    expandedAttribution
]),
target: document.getElementById('map'),
renderer: 'canvas',
overlays: [overlayPopup],
layers: layersList,
view: new ol.View({
        center: ol.proj.fromLonLat([mlon, mlat]),
        zoom: mzoom,
     maxZoom: 18, minZoom: 8
})
});

if (marker == 1) {
  var vectorLayer = new ol.layer.Vector({
    source:new ol.source.Vector({
      features: [new ol.Feature({
            geometry: new ol.geom.Point(ol.proj.transform([parseFloat(mlon), parseFloat(mlat)], 'EPSG:4326', 'EPSG:3857')),
        })]
    }),
    style: new ol.style.Style({
      image: new ol.style.Icon({
        anchor: [0.5, 0.5],
        anchorXUnits: "fraction",
        anchorYUnits: "fraction",
        src: "marker.svg"
      })
    })
  });

  map.addLayer(vectorLayer); 
}

I used the output of the qgis2web plugin and modified the file qgis2web.js as above.

Upvotes: 0

bartvde
bartvde

Reputation: 2126

Sure, see: http://openlayers.org/en/latest/examples/permalink.html for an example (uses an anchor instead of url parameters but the idea is the same).

Upvotes: 1

Related Questions