luca_papi
luca_papi

Reputation: 11

How to add Alt Tag to Images loaded via OpenLayer

I need to automatically add Alt tag to images generated automatically via Openlayer. I tried different solutions via Jquery and js, but none seems to work

How to add an alt attribute of img tags with jquery

Is there a way to add alt text to an img tag using jquery?

https://www.3schools.in/2022/04/how-to-add-alt-text-to-image-.html

Set <img> alt tag with JavaScript

jQuery add alt tag to images with same src

I tried to call by class selector and directly by tag. Unfortunatly I have no control on ID's that are dinamically generated by openlayer

here is my code

    // Size the parent iFrame
      function iframeResize() {
        var height = $('body').outerHeight(); // IMPORTANT: If body's height is set to 100% with CSS this will not work.
        parent.postMessage("resize::"+height,"*");
      }

      $(document).ready(function() {
        // Resize iframe
        setInterval(iframeResize, 1000);
      });


            var lat=46.238043
            var lon=12.4377325
            var zoom=10

            var mappa; //complex object of type OpenLayers.Map

            function initgpx() {
                mappa = new OpenLayers.Map ("mappa", {
                    controls:[
                        new OpenLayers.Control.Navigation(),
                        new OpenLayers.Control.PanZoomBar(),
                        new OpenLayers.Control.LayerSwitcher(),
                        new OpenLayers.Control.Attribution()],
                    maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34),
                    maxResolution: 156543.0399,
                    numZoomLevels: 19,
                    units: 'm',
                    projection: new OpenLayers.Projection("EPSG:900913"),
                    displayProjection: new OpenLayers.Projection("EPSG:4326")
                } );


          var grayscale = new OpenLayers.Layer.OSM('OSM Greyscale', null, {
                      eventListeners: {
                        tileloaded: function(evt) {
                            var ctx = evt.tile.getCanvasContext();
                                if (ctx) {
                                    var imgd = ctx.getImageData(0, 0, evt.tile.size.w, evt.tile.size.h);
                                    var pix = imgd.data;
                                        for (var i = 0, n = pix.length; i < n; i += 4) {
                                            pix[i] = pix[i + 1] = pix[i + 2] = (3 * pix[i] + 4 * pix[i + 1] + pix[i + 2]) / 8;
                                        }
                                        ctx.putImageData(imgd, 0, 0);
                                        evt.tile.imgDiv.removeAttribute("crossorigin");
                                        evt.tile.imgDiv.src = ctx.canvas.toDataURL();
                                    }
                                }
                            }
                        });

        mappa.addLayers([ grayscale] );
          mappa.addControl(new OpenLayers.Control.LayerSwitcher());


              var pois_Alloggi = new OpenLayers.Layer.Text( "Alloggi", { location:"https://atorinfriul.it/html/tracce_gpx/POI_Mappa/Longarone(SS51)_Vajont_Barcis(Ponte_Antoi)__POI_Alloggi.txt", projection: mappa.displayProjection});
              mappa.addLayer(pois_Alloggi);



        // Add the Layer with the GPX Track
                var lgpx = new OpenLayers.Layer.Vector("Tracciato", {strategies: [new OpenLayers.Strategy.Fixed()],
                    protocol: new OpenLayers.Protocol.HTTP({url: "https://atorinfriul.it/html/percorsi/Longarone(SS51)_Vajont_Barcis(Ponte_Antoi)__timestamp.gpx", format: new OpenLayers.Format.GPX()}),
                    style: {strokeColor: "green", strokeWidth: 5, strokeOpacity: 0.5}, projection: new OpenLayers.Projection("EPSG:4326")});
                mappa.addLayer(lgpx);



                var lonLat = new OpenLayers.LonLat(lon, lat).transform(new OpenLayers.Projection("EPSG:4326"), mappa.getProjectionObject());
                mappa.setCenter(lonLat, zoom);


            }

    function osm_getTileURL(bounds) {
            var res = this.mappa.getResolution();
            var x = Math.round((bounds.left - this.maxExtent.left) / (res * this.tileSize.w));
            var y = Math.round((this.maxExtent.top - bounds.top) / (res * this.tileSize.h));
            var z = this.mappa.getZoom();
            var limit = Math.pow(2, z);

            if (y < 0   &&   y >= limit) {
              return OpenLayers.Util.getImagesLocation() + "404.png";
            } else {
              x = ((x % limit) + limit) % limit;
              return this.url + z + "/" + x + "/" + y + "." + this.type;
            }
          }
html, body{
 width:100%;
 height:100%;
}


.olControlAttribution {
    padding: 5px;
    bottom: 0.2em !important;
    overflow: hidden;
    width: 33%;
    font-size: 1em !important;
    text-align: right;
    /* for IE */
    filter:alpha(opacity=90);
    /* CSS3 standard */
    border-radius: 4px;
}
<!DOCTYPE html>
<html lang="it">

  <head>
    <meta http-equiv="content-type" content="text/html; charset=windows-1252">

    <meta http-equiv="Cache-control" content="public, max-age=31536000, immutable">

      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">

         <!-- JS sezione Mappa POI's -->
         <script src="https://atorinfriul.it/html/js/lib/OpenLayers.js"></script>
        <script src="https://atorinfriul.it/html/js/OpenStreetMap.js"></script>

    <!-- bring in the OpenStreetMap OpenLayers layers. Using this hosted file will make sure we are kept up      to date with any necessary changes -->



    <script type='text/javascript' src="https://atorinfriul.it/html/js/jquery.min.js"></script>

  </head>
  <!-- body.onload is called once the page is loaded (call the 'init' function) -->
  <body onload="initgpx();"> <!-- define a DIV into which the map will appear. Make it take up the whole window -->



  <div style="width:100%;  height:90% ;border: 1px solid blue; background: url('https://atorinfriul.it/html/images/caricamento.gif') no-repeat center center;  background-size: cover;" id="mappa"></div>
<script type="text/javascript">
$(function(){
jQuery(document).ready(function() {

//$('#mappa > img[alt]').attr('image');

$('img').attr('alt', 'Whatever you want');

//$('img:not([alt])').attr('alt', 'logo');

});
});
</script>





  </body>
</html>

In bottom section I left my unsuccessful tries, uncommenting previous.

I noted, in snippet, map did't show gpx track and poi icon, but on real file them working perfect

in addition: I use Openlayer 2.31 and check result via https://pagespeed.web.dev/

Thanks for any suggestion

Upvotes: 1

Views: 81

Answers (0)

Related Questions