-1

I'm facing some problems with jquery and javascript interoperability.

I have a piece of code that attempts to create a PNG from the canvas and write it to a variable.

jQuery.getScript('https://api.tiles.mapbox.com/mapbox-gl-js/v0.44.1/mapbox-gl.js', function() {
    //script is loaded and executed put your dependent JS here
    mapboxgl.accessToken = '<ACCESS_TOKEN>';
    var mapcanvas = new mapboxgl.Map({
        container: 'mapimg',
        style: 'mapbox://styles/mapbox/streets-v9',
        lon: center[1].toFixed(6),
        lat: center[0].toFixed(6),
        zoom: zoominfo.zoom,
        preserveDrawingBuffer: true
    });

    var getbasemapimg = mapcanvas.getCanvas().toDataURL('image/png');
    alert("Inside jQuery: " + getbasemapimg);
});

This works fine inside the jQuery section above (the alert returns getbasemapimg in its base64 string format), but further along in the script, I attempt to call the getbasemapimg variable and this time it says it's undefined: getbasemapimg is not defined

I had to wrap the first section up in jQuery as it was calling an external javascript source and I could figure out how to get it to work without employing jQuery.

I think I need to set the value getbasemapimg globally but can't work out how to do it.

Pushprajsinh Chudasama
  • 7,772
  • 4
  • 20
  • 43
Huskie69
  • 795
  • 3
  • 11
  • 31
  • 1
    where are you calling the variable, share that code. Either you can make variable global or you can pass it as function parameter – Bhushan Kawadkar Oct 11 '19 at 10:45
  • 1
    Scope is related to the place of declaration in javascript. To make it global scope, place it at top most level. Refer [this](https://www.geeksforgeeks.org/understanding-variable-scopes-in-javascript/) for more information. – Ms.Tamil Oct 11 '19 at 10:46

1 Answers1

1

You need to have access to mapboxgl in your scope. Your code is called as a callback after the library is requested via Ajax. You can add that library in your index.html via a tag BEFORE your own code as a simple solution to your problem.