-1

I've developed a javascript file called service.js that creates a map of mapbox, but I want to reduce my code calling from my file service.js to other file to get a var that contains a json.

I have var no_base_map = {...}; in a file called no_base_map.js and I want import that attribute inside my function as case 'nobase: return no_base_map;'

But I dont know how import that javascript file inside service.js, how can reference it?

function getBaseMap(name) {

    switch(name) {
        case 'nobase': return getNoBaseMap();
        default:
            return getNoBaseMap();
    }

};

function getNoBaseMap() {
    var no_base_map =
    {
        "version": 8,
        "name": "NO_BASE_MAP",
        "metadata": { },
        "center": [
            1.537786,
            41.837539
        ],
        "zoom": 12,
        "bearing": 0,
        "pitch": 0,
        "sources": {},
        "layers": [],
        "id": "no-base-map"
    };
    return no_base_map;
};

Maybe I dont explain well... I'm not using react, angular, express to add other file with import o require. Is a javascript loaded from html file.

As you can see here is my html file:

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8' />
    <title>Map Generator</title>
    <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
    <script src='module/service.js'></script>
    <script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.46.0/mapbox-gl.js'></script>
    <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.46.0/mapbox-gl.css' rel='stylesheet' />
    <style>
        body { margin:0; padding:0; }
        #map { position:absolute; top:0; bottom:0; width:100%; }
    </style>
</head>
<body>
    <div id="map"></div>
    <script>
        myCustomMap.addMap("5b4f12233cfb101f4c2d0537", "map");
    </script>
</body>
</html>

And this is my Service.js

var myCustomMap = {

    addMap: function(id, target) {
        sendRequest(id)
        .then( (data) => {
            // Create Map
            return createMap(data, target);
        })
        .then( (info) => {
            // Add Controls
            addControls(info.map);
            return info;
        })
        .then( (info) => {
            // Add Layers
            addLayers(info.map, info.layers);
        })
        .catch( (err) => {
            console.log('Error: ', err);
        });
    }
};

function sendRequest(id) {
    return new Promise( (resolve, reject) => {
        var url = 'http://localhost:8080/map/' + id;
        fetch(url)
        .then( (res) => res.json())
        .then( (data) => {
            if (data.ok) {
                resolve(data.map);
            } else {
                reject(data.error);
            }
        })
        .catch( (err) => {
            reject(err);
        });
    });   
};

function createMap(info, target) {
    // var base = String(info.base); // info.base = 'nobase'
    var base = 'nobase'; // info.base = 'nobase'
    var lat = Number(info.lat);
    var lng = Number(info.lng);
    var zoom = Number(info.zoom);
    var layers = info.wmslayers;

    var map = new mapboxgl.Map({
        container: String(target), // container id
        style: getBaseMap(base), // stylesheet location
        center: [lng, lat], // starting position [lng, lat]
        zoom: zoom // starting zoom
    });

    return { map: map, layers: layers };
};

function addControls(map) {
    navigationControl(map);
    addScaleControl(map);
    addLocationControl(map);
};

function navigationControl(map) {
    var nav = new mapboxgl.NavigationControl();
    map.addControl(nav, 'top-right');
};

function addScaleControl(map) {
    var scale = new mapboxgl.ScaleControl({
        maxWidth: 80,
        unit: 'metric'
    });
    map.addControl(scale);
};

function addLocationControl(map) {
    map.addControl(new mapboxgl.GeolocateControl({
        positionOptions: {
            enableHighAccuracy: true,
            watchPosition: true
        },
        trackUserLocation: true
    }));
};

function addLayers(map, layers) {
    if (layers.length > 0) {
        layers.reverse().forEach(layer => {

            map.on('load', function() {
                map.addLayer({
                'id': String(layer.keyName), 'type': 'raster',
                'source': { 'type': 'raster', 'tiles': [ createUrl(layer) ], 'tileSize': 256 }
                });
            });

        });
    }
};

function createUrl(layer) {
    var fullUrl;
    if (!layer.hasFilter) {
        fullUrl = `${layer.url}bbox={bbox-epsg-3857}&format=${layer.format}&styles=${layer.styles}&transparent=true&service=WMS&version=${layer.version}&request=GetMap&${(layer.version.localeCompare('1.3.0') === 0) ? 'crs' : 'srs' }=EPSG:3857&width=256&height=256&layers=${layer.layers}&map=${layer.aditionals}`;
    } else {
        fullUrl = `${layer.url}bbox={bbox-epsg-3857}&format=${layer.format}&styles=${layer.styles}&transparent=true&service=WMS&version=${layer.version}&request=GetMap&${(layer.version.localeCompare('1.3.0') === 0) ? 'crs' : 'srs' }=EPSG:3857&width=256&height=256&layers=${layer.layers}&map=${layer.aditionals}&CQL_FILTER=${layer.code}='${layer.filter}'`;
    }
    return fullUrl;
};

function getBaseMap(name) {

    switch(name) {
        case 'nobase': return getNoBaseMap();
        default:
            return getNoBaseMap();
    }

};

function getNoBaseMap() {
    var no_base_map =
    {
        "version": 8,
        "name": "NO_BASE_MAP",
        "metadata": { },
        "center": [
            1.537786,
            41.837539
        ],
        "zoom": 12,
        "bearing": 0,
        "pitch": 0,
        "sources": {},
        "layers": [],
        "id": "no-base-map"
    };
    return no_base_map;
};

I want to have getNoBaseMap function in other file.

export function no_base() {
    return {
        "version": 8,
        "name": "NO_BASE_MAP",
        "metadata": {
        },
        "center": [
        1.537786,
        41.837539
        ],
        "zoom": 12,
        "bearing": 0,
        "pitch": 0,
        "sources": {},
        "layers": [],
        "id": "no-base-map"
    };
};

How can add that function to my service.js?? If I try with import than it shows me this:

Uncaught SyntaxError: Unexpected token {

Kiran Joshi
  • 944
  • 2
  • 7
  • 25
Javier
  • 1,409
  • 1
  • 14
  • 30
  • If you are using jquery then can use $.getScript – Ullas Hunka Jul 19 '18 at 10:06
  • Possible duplicate of [How do I include a JavaScript file in another JavaScript file?](https://stackoverflow.com/questions/950087/how-do-i-include-a-javascript-file-in-another-javascript-file) – tom johnes Jul 19 '18 at 10:06
  • Typically it is done using `import` statements (ES6), but you cannot if it is client side Javascript. You would have to use a bundler like Webpack to read all your imports and put them into one file. – minitauros Jul 19 '18 at 10:06
  • Possible duplicate of [How to Append in javascript?](https://stackoverflow.com/questions/9413737/how-to-append-script-script-in-javascript) – Ullas Hunka Jul 19 '18 at 10:07
  • Check here: https://stackoverflow.com/questions/950087/how-do-i-include-a-javascript-file-in-another-javascript-file https://stackoverflow.com/questions/14521108/dynamically-load-js-inside-js – Andrew K Jul 19 '18 at 10:12
  • But I'm not using react, angular, exprees... is a javascript file. – Javier Jul 19 '18 at 10:12

1 Answers1

1

You can call the function from one javascript file to other. Just simply include the script source in html as following

temp.js

function getBaseMap(name) {

switch(name) {
    case 'nobase': return getNoBaseMap();
    default:
        return getNoBaseMap();
}

};

function getNoBaseMap() {
var no_base_map =
{
    "version": 8,
    "name": "NO_BASE_MAP",
    "metadata": { },
    "center": [
        1.537786,
        41.837539
    ],
    "zoom": 12,
    "bearing": 0,
    "pitch": 0,
    "sources": {},
    "layers": [],
    "id": "no-base-map"
};
return no_base_map;
};

html file

<!DOCTYPE html>
    <html>
        <head>
            <meta charset='utf-8' />
            <title>Map Generator</title>
            <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />



            <script src="temp.js"></script>
            <script src='module/service.js'></script>

            <script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.46.0/mapbox-gl.js'></script>
            <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.46.0/mapbox-gl.css' rel='stylesheet' />
            <style>
                body { margin:0; padding:0; }
                #map { position:absolute; top:0; bottom:0; width:100%; }
            </style>
        </head>
    <body>
        <div id="map"></div>
        <script>
            myCustomMap.addMap("5b4f12233cfb101f4c2d0537", "map");
        </script>
    </body>
</html>

And your file server.js will be as it is.

As you have included the temp.js file first in html file, so, you can call the function from temp.js in service.js

So, you can call the function from temp.js in service.js

Please let me know if it worked.

Abdul Jabbar
  • 338
  • 2
  • 9
  • No, navigator says: Uncaught SyntaxError: Unexpected token – Javier Jul 19 '18 at 10:30
  • Please let me know the name of first js file and name of second js file – Abdul Jabbar Jul 19 '18 at 10:36
  • In my html file I call my js file inside this js file, I want to call other js file that contains a var, it doesnt matter the name, for example: no_base_map.js – Javier Jul 19 '18 at 10:43
  • I've updated the answer. Please have a look on it and then please let me know. Thanks – Abdul Jabbar Jul 19 '18 at 11:01
  • Yes, It works nad I did the same but... that I want, I want that html file only load service js file and dont know anything about the other js files with map information – Javier Jul 19 '18 at 11:22
  • You must have at least name of other js file (which contains map information) to call the function from that file. – Abdul Jabbar Jul 19 '18 at 11:24