简体   繁体   中英

How to define zoom button in openlayers API?

How can I remove default ol-zoom buttons and define another zoom buttons with different tags and class names in openlayers API?

<div class="ol-zoom ol-unselectable ol-control">
    <button class="ol-zoom-in" type="button" title="Zoom in">+</button>
    <button class="ol-zoom-out" type="button" title="Zoom out">−</button>
</div>

I used this code to set CSS class name for zoom buttons but I dont know why it doesn't work :

new ol.control.Zoom({
          className: "my-new-class-name"
        });

I cannot see if you actually added the Zoom control to the map. Instantiating the control itself does not change the OL map. Also, the map has a default zoom control instance. If you called addControl on the map, you might have ended up with two zoom controls being placed above each other.

You can give your control as a option to the map initialization. If you do not want to list all other controls manually, just use ol.control.defaults with the option zoom: false . It omits the zoom control but adds the default attribution and rotation controls.

You could even give your options directly to the ol.control.defaults:

ol.control.defaults({
    zoomOptions: {
        className: "ol-zoom my-new-class-name"
    }
})

Secondly, setting the className is not additive, it replaces the default ol-zoom class. So your control might be added to the DOM, but has no styling and is placed offscreen. You can fix that by adding ol-zoom to the className too.

Here is a working example:

 var map = new ol.Map({ controls: ol.control.defaults({ zoom: false }).extend([ new ol.control.Zoom({ className: "ol-zoom my-new-class-name" }) ]), layers: [ new ol.layer.Tile({ source: new ol.source.OSM() }) ], target: 'map', view: new ol.View({ center: [0, 0], zoom: 3, }) }); 
 .ol-zoom.my-new-class-name { background: red; } 
 <link href="https://openlayers.org/en/v4.6.4/css/ol.css" rel="stylesheet"/> <script src="https://openlayers.org/en/v4.6.4/build/ol-debug.js"></script> <div id="map" class="map"></div> 

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