primero agradecer a todos por visualizar la pregunta e intentar resolver mi duda.
Estoy desarrollando un fichero en typescript en el que realice la función de cargar un mapa desde un html. El cual cargará el fichero javascript compilado por typescript y que recibirá dos parámetros: "el id del mapa" y "el target del div donde se mostrará".
Primero lo realicé en Javascript, pero mi idea es hacerlo en typescript para importar las librerías y mapas de fondo por defecto para que los usuarios no vean cómo se ejecuta, sino que únicamente cargue el fichero js y desde el html llame a una función y cargue todo.
Lo que he hecho ha sido crear un fichero index.js donde hago las importaciones e implemento el código. Después, desde la consola escribo: tsc
y me genera en la carpeta dist el fichero index.js y una carpeta con los mapas de fondo.
Eso lo llevo a una carpeta donde esta el html y añado la ruta al fichero index.js
Pero abro el navegador y me muestra los siguientes errores:
Uncaught ReferenceError: exports is not defined at index.js:5
Uncaught TypeError: Cannot read property 'addMap' of undefined at index.html:19
Mi fichero index.ts es el siguiente:
import { no_base_map } from './maps/no_base_map';
import { fulldark_map } from './maps/fulldark_map';
import { hibrid_map } from './maps/hibrid_map';
import { icgc_map } from './maps/icgc_map';
import { night_map } from './maps/night_map';
import { osm_map } from './maps/osm_map';
import { positron_map } from './maps/positron_map';
import { satellite_hibrid } from './maps/satellite_hibrid';
import mapboxgl from 'mapbox-gl';
var axisMap = {
addMap: function(id:String, target:String) {
sendRequest(id)
.then( (data) => {
console.log(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:String) {
return new Promise( (resolve, reject) => {
var url = 'http://localhost:8080/map/' + id;
console.log('url: ', url);
fetch(url)
.then( (res) => res.json())
.then( (data) => {
console.log('data server: ', data);
if (data.ok) {
resolve(data.map);
} else {
reject(data.error);
}
})
.catch( (err) => {
reject(err);
});
});
};
function createMap(info:any, target:String) {
var base = String(info.base); // info.base = 'nobase'
var lat = Number(info.lat);
var lng = Number(info.lng);
var zoom = Number(info.zoom);
var layers = info.wmslayers;
mapboxgl.accessToken = 'my_access_token';
var map = new mapboxgl.Map({
container: String(target), // container id
style: String(getBaseMap(base)), // stylesheet location
center: [lng, lat], // starting position [lng, lat]
zoom: zoom // starting zoom
});
return { map: map, layers: layers };
};
function addControls(map:any) {
navigationControl(map);
addScaleControl(map);
addLocationControl(map);
};
function navigationControl(map:any) {
var nav = new mapboxgl.NavigationControl();
map.addControl(nav, 'top-right');
};
function addScaleControl(map:any) {
var scale = new mapboxgl.ScaleControl({
maxWidth: 80,
unit: 'metric'
});
map.addControl(scale);
};
function addLocationControl(map:any) {
map.addControl(new mapboxgl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true,
timeout: 300
},
trackUserLocation: true
}));
};
function addLayers(map:any, layers:any) {
if (layers.length > 0) {
layers.reverse().forEach( (layer:any) => {
map.on('load', function() {
map.addLayer({
'id': String(layer.keyName), 'type': 'raster',
'source': { 'type': 'raster', 'tiles': [ createUrl(layer) ], 'tileSize': 256 }
});
});
});
}
};
function createUrl(layer:any) {
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:String) {
switch(name) {
case 'openstreetmaps': return osm_map;
case 'icgc': return icgc_map;
case 'positron': return positron_map;
case 'fulldark': return fulldark_map;
case 'night': return night_map;
case 'hibrid': return hibrid_map;
case 'nobase': return no_base_map;
case 'hibrid': return satellite_hibrid;
default:
return no_base_map;
}
};
Este es mi fichero HTML:
<!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='js/index.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:50%; height: 50%; }
</style>
</head>
<body>
<div id="map"></div>
<script>
axisMap.addMap("5b4f12233cfb101f4c2d0537", "map");
</script>
</body>
</html>
Y despues de hacer tsc
en la consola me genera esto, no pondré todo el código. Únicamente las primeras líneas para que veais porque me muestra dichos errores.
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const no_base_map_1 = require("./maps/no_base_map");
const fulldark_map_1 = require("./maps/fulldark_map");
const hibrid_map_1 = require("./maps/hibrid_map");
const icgc_map_1 = require("./maps/icgc_map");
const night_map_1 = require("./maps/night_map");
const osm_map_1 = require("./maps/osm_map");
const positron_map_1 = require("./maps/positron_map");
const satellite_hibrid_1 = require("./maps/satellite_hibrid");
const mapbox_gl_1 = __importDefault(require("mapbox-gl"));
var axisMap = {
addMap: function (id, target) {
sendRequest(id)
.then((data) => {
console.log(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;
console.log('url: ', url);
fetch(url)
.then((res) => res.json())
.then((data) => {
console.log('data server: ', data);
if (data.ok) {
resolve(data.map);
}
else {
reject(data.error);
}
})
.catch((err) => {
reject(err);
});
});
}
;
....
Gracias por su ayuda
Mi fichero tsconfig.json
{
"compilerOptions": {
/* Basic Options */
"target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "dist", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
/* Source Map Options */
// "sourceRoot": "./", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "./", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
}
}
EDICIÓN: NUEVO PROPBLEMA
Ahora he creado una clase e importo por ejemplo un mapa
import { no_base_map } from './maps/no_base_map';
class AxisMap {
constructor(id: string, target: string) {
this.addMap(id, target);
}
addMap(id:string, target:string): void {
this.sendRequest(id)
.then( (data:any) => {
// Create Map
return this.createMap(data, target);
})
.then( (info:any) => {
// Add Controls
this.addControls(info.map);
return info;
})
.then( (info:any) => {
// Add Layers
this.addLayers(info.map, info.layers);
})
.catch( (err:any) => {
console.log('Error: ', err);
});
}
sendRequest(id:string) {
return new Promise( (resolve:any, reject:any) => {
var url = 'http://localhost:8080/map/' + id;
fetch(url)
.then( (res) => res.json())
.then( (data) => {
console.log('data server: ', data);
if (data.ok) {
resolve(data.map);
} else {
reject(data.error);
}
})
.catch( (err) => {
reject(err);
});
});
}
createMap(info:any, target:string) {
var base = String(info.base); // info.base = 'nobase'
var base = String('nobase'); // info.base = 'nobase'
var lat = Number(info.lat);
var lng = Number(info.lng);
var zoom = Number(info.zoom);
var layers = info.wmslayers;
mapboxgl.accessToken = 'my_access_token';
var style = this.getBaseMap(base);
var map = new mapboxgl.Map({
container: String(target),
// style: String(this.getBaseMap(base)), // stylesheet location
style: String(style),
// style: 'mapbox://styles/mapbox/streets-v9',
center: [lng, lat],
zoom: zoom // starting zoom
});
return { map: map, layers: layers };
}
addControls(map:any) {
this.navigationControl(map);
this.addScaleControl(map);
this.addLocationControl(map);
}
navigationControl(map:any) {
var nav = new mapboxgl.NavigationControl();
map.addControl(nav, 'top-right');
}
addScaleControl(map:any) {
var scale = new mapboxgl.ScaleControl({
maxWidth: 80,
unit: 'metric'
});
map.addControl(scale);
}
addLocationControl(map:any) {
map.addControl(new mapboxgl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true,
timeout: 300
},
trackUserLocation: true
}));
}
addLayers(map:any, layers:any) {
if (layers.length > 0) {
layers.reverse().forEach( (layer:any) => {
let fullUrl = this.createUrl(layer);
map.on('load', function() {
map.addLayer({
'id': String(layer.keyName), 'type': 'raster',
'source': { 'type': 'raster', 'tiles': [ fullUrl ], 'tileSize': 256 }
});
});
});
}
}
createUrl(layer:any) {
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;
}
getBaseMap(name:String) {
switch(name) {
case 'nobase': return no_base_map;
default:
return no_base_map;
}
}
}
Después de hacer tsc
en la consola me genera el javascript peeeero, me muestra lo siguiente en el fichero index.js:
import { no_base_map } from './maps/no_base_map';
class AxisMap {
constructor(id, target) {
this.addMap(id, target);
}
El nombre de la clase AxisMap se oscurece, como si después del import no interpretara más código.
Y me muestra los siguientes errores: - Uncaught SyntaxError: Unexpected token { at index.js 1 - Uncaught ReferenceError: AxisMap is not defined at (index):18
No lo entiendo :(