简体   繁体   中英

How to display, center and zoom a map using OpenLayers?

I started learning the OpenLayers and GeoServer. The layer is added at GeoServer using the OSM shape file which is indicated as EPSG:4326 with bounds [68.5094575, 6.6791812, 97.0315678, 35.3123975] . Using OpenLayers this layer is obtained as WMS and getting displayed.

For displaying the map the following line of code is used:

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

Now the map is getting displayed. But when I use the below code, the map is not getting displayed:

map.getView().fit(bounds, map.getSize());
map.getView().setCenter(ol.proj.transform[77.216574, 28.627671], 'EPSG:4326', 'EPSG:3857'));
map.getView().setZoom(5);

Thanks in advance.

You have a syntax error:

map.getView().setCenter(ol.proj.transform[77.216574, 28.627671], 'EPSG:4326', 'EPSG:3857'));

should be:

map.getView().setCenter(ol.proj.transform([77.216574, 28.627671], 'EPSG:4326', 'EPSG:3857'));

If I change that and remove the map.getView().fit(bounds, map.getSize());

The map works:

 html, body { height: 100%; width: 100%; padding: 0px; margin: 0px; } .map { height: 95%; width: 100%; } 
 <link rel="stylesheet" href="https://openlayers.org/en/v5.3.0/css/ol.css" type="text/css"> <script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script> <div id="map" class="map"></div> <script> var map = new ol.Map({ layers: [ new ol.layer.Tile({ // TileLayer({ source: new ol.source.OSM() }) ], target: 'map', view: new ol.View() }); map.getView().setCenter(ol.proj.transform([77.216574, 28.627671], 'EPSG:4326', 'EPSG:3857')); map.getView().setZoom(5); </script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM