1

I am using OpenLayers 3 to build a 'spy glass' map, with an old map selectively visible over an OSM layer. The spy glass element follows the mouse around the map to reveal the old map.

I'm now trying to get the spy glass to sit at the center of the map when the page first loads, and then follow the mouse when it enters the map area. Besides looking a lot nicer and making the purpose of the map more obvious, it's a great solution for mobile usage, as in the absence of mouse input the spy glass then stays in the center and the map can be rotated around it.

I've been able to shift the default placement of the spy glass onto the map though setting pixel values

var mousePosition = [300,300];

but haven't succeeded in finding a way to calculate the center and pass it to the function. I've tried some functions, including the current combination of

var center = map.getView().getCenter();
var pixel = map.getPixelFromCoordinate(center);
var mousePosition = pixel;

but with no effect.

The following JSFiddle has the full code: http://jsfiddle.net/o3px0u8y/1/

How can I set the spy glass to first load in the center of the map?

1

I managed to resolve this using the postrender function:

map.once('postrender', function() {
var pixel = map.getPixelFromCoordinate(map.getView().getCenter());

I've updated the JSFiddle here: https://jsfiddle.net/o3px0u8y/1/. Note that the closing brackets for

map.once('postrender', function() {

are all the way down at the end of the code.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.