Save OpenLayers map as a PNG file using a personalized file name

I am trying to save my map as a .png image but I am encountering some difficulties. The code I have been using is supposed to allow me to do so, but it seems like there might be something missing because I cannot save the image under a custom name.

document.getElementById('export-png').addEventListener('click', function () {
  map.once('rendercomplete', function () {
  var mapCanvas = document.createElement('canvas');
  var size = map.getSize();
  mapCanvas.width = size[0];
  mapCanvas.height = size[1];
  var mapContext = mapCanvas.getContext('2d');
  Array.prototype.forEach.call(
  document.querySelectorAll('.ol-layer canvas'),
  function (canvas) {
    if (canvas.width > 0) {
      var opacity = canvas.parentNode.style.opacity;
      mapContext.globalAlpha = opacity === '' ? 1 : Number(opacity);
      var transform = canvas.style.transform;
      // Get the transform parameters from the style's transform matrix
      var matrix = transform
        .match(/^matrix\(([^\(]*)\)$/)[1]
        .split(',')
        .map(Number);
      // Apply the transform to the export map context
      CanvasRenderingContext2D.prototype.setTransform.apply(
        mapContext,
        matrix
      );
      mapContext.drawImage(canvas, 0, 0);
    }
  }
 );
 if (navigator.msSaveBlob) {
   // link download attribuute does not work on MS browsers
   var imgName = prompt("Please provide the name", "survey_map");
   navigator.msSaveBlob(mapCanvas.msToBlob(), imgName + '.png');
 } else {
   var link = document.getElementById('image-download');
   link.href = mapCanvas.toDataURL();
   link.click();
 }
});
 map.renderSync();
 });

I tried using the prompt property to set a custom name for the image, but unfortunately, it did not work in this case.

https://i.sstatic.net/ynjSW.png

Is there a way to successfully save the .png image with a custom name?

Answer №1

If you want your code to be compatible with various browsers, not just Internet Explorer and the old Edge, you should make sure to set the download attribute of the link. Additionally, it's important to check if the cancel button was clicked to avoid downloading a file named null.png unintentionally.

 var imageName = prompt("Please enter a name", "survey_map");
 if (imageName) {
   if (navigator.msSaveBlob) {
     // The link's download attribute does not function on Microsoft browsers
     navigator.msSaveBlob(mapCanvas.msToBlob(), imageName + '.png');
   } else {
     var downloadLink = document.getElementById('image-download');
     downloadLink.download = imageName + '.png';
     downloadLink.href = mapCanvas.toDataURL();
     downloadLink.click();
   }
 }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Emphasize the engaged menu selection when the page is refreshed

My application is a dashboard app built with React, Redux, and Antdesign. I utilized the layout provided by Ant design at https://ant.design/components/layout/. One issue I encountered is that when clicking on side menus, the active menu gets bold but upo ...

``The ngRoute module is causing issues with loading in my application

Just delved into the world of AngularJS and encountered a challenging 'Routing' assignment for some hands-on practice. To my disappointment, I encountered a couple of errors when running the application: Error 1: Error: $injector:modulerr Mo ...

substitute bullet point list item with new element

Assuming I have a list: <ul class="ul-1"> <li class="li-1">xx -1</li> <li class="li-2">xx -2</li> <li class="li-3">xx -3</li> </ul> Then I store it as: var list = $('.ul-1').html(); In ...

Storing data securely with Firebase: Executing the task 'uploadBytes'

I am currently learning how to use Firestore for my database. I have been trying to send data from state to the database, but I keep encountering an error message that says "uploadBytes" cannot be performed on a root reference. Since I am not very familiar ...

Discovering Unconventional Columns Through Sharepoint REST Api Filtration

I am working on recreating SharePoint's front end in my app and want to add columns to my table just like a user would in SP. The challenge I am facing is determining which columns were custom generated by the user rather than standard ones. Although ...

Steps to dynamically modify an HTML element within an Android WebView

https://www.bing.com/search?q=кму here I want to switch the bing icon to google I attempted : if (url == "https://www.bing.com/search?q=") { view.evaluateJavascript( ("\n"+ "wind ...

"Navigate through the page by scrolling with your mouse all the way to 100

Is it possible to trigger an action when a user starts scrolling using the mousewheel? I've searched online but all I found was information on 100% scroll on click. I want the window to automatically be scrolled down to 100% as soon as the user starts ...

Javascript functions triggering repeatedly

I'm working on creating a fun trivia quiz using JavaScript functions. Each question involves globally defined functions called "right" and "wrong" that are supposed to update the score accordingly. However, I've run into an issue where the quiz s ...

Stop the initial expansion of the first accordion with JavaScript on page load

I have a simple accordion created using only pure javascript without jQuery and Pure CSS. Everything is functioning correctly, but the problem I am facing is that the first accordion is automatically expanded when the page loads. I have tried various metho ...

What are the steps to utilize chrome.tabs.onUpdated.addListener?

I am currently working on a Chrome extension where I need to display an alert() showing the page URL whenever the user switches tabs or enters a new URL in a tab. However, my current implementation is not functioning as expected: chrome.tabs.onUpdated.ad ...

Is there a way to execute a JavaScript function on a webpage using Selenium automation?

Here's an element on a website: <span class="log-out-ico" ng-click="logout()"> Instead of clicking it, I want to run the "logout()" script from selenium. Is that possible? If so, how can I do it? This is what I attempted: I ...

How can a script be properly embedded into an HTML document?

Currently, I am facing an unusual issue with the script tags in my Django project. My layout.html file includes Jquery and Bootstrap in the head section. Using Jinja, I extended layout.html to create a new file called main.html. In main.html, I added a new ...

Managing extensive geographical information through HTTP

What is the most efficient way to transmit a substantial volume of map information via HTTP for rendering on the client side? There must be a more effective approach than simply transmitting a JSON file containing all map data. I am interested in how maj ...

Retrieve the values from the getJSON request and provide a list

Need to search through a vast JSON file for a specific match on my webpage. The file is jam-packed with various values and objects, structured like this: name: john doe, id: 5891, description: product, name: jane doe, id: 5892, description: product, and ...

Issue in IE11 with pdf.js: src property (0x800a138f)

My application uses pdf.js to display PDF files, and everything works smoothly except for one issue with Internet Explorer. Whenever I try to start the app on IE, an exception is thrown: Unhandled exception at line 8290, column 5 in http://.../scripts/pdf ...

How come defining the state using setTimeout does not display the accurate properties of a child component?

Presented here is a component designed to render a list of items and include an input for filtering. If no items are present or if the items are still loading, a message should be displayed. import { useState } from "react"; export const List = ...

Error message occurs when creating a pie chart with invalid values for the <path> element in Plottable/D3.js

For those who need the code snippets, you can find them for download here: index.html <!doctype html> <html> <head> <meta charset="UTF-8"> <!-- CSS placement for legend and fold change --> </head> <body ...

Determining the necessary data to send via ajax for a particular issue

Currently, I am learning JavaScript and have encountered another challenge along the way. I am looking for assistance in understanding the concept, whether it is a solution in jQuery or Angular. I have two types of tasks in my HTML - audio or graphic. The ...

How to integrate a new DOM element into a React Native app with the simple click of a button

Is it possible to add a <Text> element with the click of a button in react native? If so, how can this be achieved? Here is my current code: import React, { Component } from 'react' import { StyleSheet, Text, View, Button } from &apos ...

What are the different ways to programmatically change CSS rules using JavaScript in a Firefox Add-on, leveraging XUL, SDK, or WebExtensions methods?

Looking to dynamically alter a CSS rule set through JavaScript within a Firefox Add-on using XUL, SDK or WebExtensions techniques. Specifically targeting support for Firefox versions 29.0b1 through 49.0a1. The main issue I want to address is modifying the ...