OpenLayers 3: Zoom map to coordinates in array

三世轮回 提交于 2019-12-24 07:50:11

问题


I need to zoom my OpenLayers map (which uses a Google Maps baselayer) to fit all of a given list of coordinates into the view.

I've stored the coordinates in an array of longitude and latitude pairs named pointsDecimal which looks like this:

pointsDecimal: Array[50]
  0: 148.77638
  1: -34.491728
  2: 148.77896
  3: -34.492302
  4: 148.778090711323
  ...

Even-numbered indices (0, 2, 4 etc) are longitude, and odd-numbered indices (1, 3, 5 etc) are latitude.

This is the code I'm trying to use:

map.getView().fit(pointsDecimal, map.getSize());

But for some reason this puts me at maximum zoom level at the coordinates [0,0] - in the Gulf of Guinea, not in southeastern New South Wales where I'd like to be!

I know this would be much easier if I was using an OpenLayers source (e.g. source.getExtent()) in place of my pointsDecimal array, but this is not an option in this case for reasons I won't go into right now - I can only use the array.

Can anyone give me any hints please?

EDIT: I think I'm nearly there, thanks to Anupam. This is what I have now:

var extent = [pointsLongMin,pointsLatMin,pointsLongMax,pointsLatMax];
map.getView().fit(extent,map.getSize());

The values I'm passing to the array are as follows:

pointsLongMin: 148.771162
pointsLatMin: -34.5029736405108
pointsLongMax: 148.77896
pointsLatMax: -34.491728

But I'm still getting dumped out in the ocean at [0,0]. What am I doing wrong here?


回答1:


In order to use map.getView().fit(extent,size). extent denotes four points as [minx, miny, maxx,maxy].

It is actually a rectangle. try

var extent=[148.77638,-34.491728,148.77896,-34.492302];

map.getView().fit(extent,map.getSize());



回答2:


most propable reason is that your map is projected on EPSG:3857while your extent EPSG:4326. So you need to transform your extent to your map projection.

var coordMin = ol.proj.fromLonLat([148.77638,-34.491728], 'EPSG:3857');
var coordMax = ol.proj.fromLonLat([148.77896,-34.492302], 'EPSG:3857');
var extent=[coordMin[0],coordMin[1],coordMax[0],coordMax[1]];
map.getView().fit(extent,map.getSize());

You may find a more elegand way to do the extent transformation. Unless you provide your full code we can only guess what is your map projection. I am just guessing is EPSG:3857 cause thats the default ol3 use.



来源:https://stackoverflow.com/questions/38291471/openlayers-3-zoom-map-to-coordinates-in-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!