我在5.12.2上将一些javascript库与QML一起使用。其中一些工作类似于Proj4JS。但是将geographiclib.js库与QML一起使用时出现错误。如何将JavaScript库导入QML?
main.qml:
import QtQuick 2.12
import QtQuick.Window 2.12
import "geographiclib.js" as MyGeo
Window {
visible: true
width: 640
height: 480
Component.onCompleted: {
var Geodesic = MyGeo.GeographicLib.Geodesic,
DMS = MyGeo.GeographicLib.DMS,
geod = Geodesic.WGS84;
var r = geod.Inverse(23, 22, 44, 29);
console.log("distance is: ", r.s12.toFixed(3) + " m")
}
}
错误:
qrc:/geographiclib.js:3081: ReferenceError: window is not defined
qrc:/main.qml:9: TypeError: Cannot read property 'Geodesic' of undefined
答案 0 :(得分:2)
最简单的方法是使GeographicLib
在全球范围内可用:
在 geographiclib.js 文件的末尾,更改
window.GeographicLib = geo;
到
this.GeographicLib = geo;
然后您可以使用:
main.qml:
import QtQuick 2.12
import QtQuick.Window 2.12
import "geographiclib.js" as ThenItWillBeAvailableGlobally
Window {
visible: true
width: 640
height: 480
Component.onCompleted: {
var Geodesic = GeographicLib.Geodesic,
DMS = GeographicLib.DMS,
geod = Geodesic.WGS84;
var r = geod.Inverse(23, 22, 44, 29);
console.log("distance is: ", JSON.stringify(r))
}
}
结果:
qml: distance is: {"lat1":23,"lat2":44,"lon1":22,"lon2":29,"a12":21.754466225665134,"s12":2416081.7576307985,"azi1":13.736139413215236,"azi2":17.669059640534535}
如果您根本不想更改 geographiclib.js 文件,则可以使用以下方式添加全局窗口对象:
window.js:
this.window = this;
然后使用:
import QtQuick 2.12
import QtQuick.Window 2.12
import "window.js" as ThenWindowWillBeAvailableGlobally
import "geographiclib.js" as ThenGeographicLibWillBeAvailableGlobally
Window {
visible: true
width: 640
height: 480
Component.onCompleted: {
var Geodesic = GeographicLib.Geodesic,
DMS = GeographicLib.DMS,
geod = Geodesic.WGS84;
var r = geod.Inverse(23, 22, 44, 29);
console.log("distance is: ", JSON.stringify(r))
}
}
如果您不想添加任何全局变量,但是很高兴编辑 geographiclib.js 文件,则只需将第68行移到文件顶部即可。
var GeographicLib = {};
/*
* Geodesic routines from GeographicLib translated to JavaScript. See
* https://geographiclib.sourceforge.io/html/js/
并在文件更改结束时
} else {
/******** otherwise just pollute our global namespace ********/
window.GeographicLib = geo;
}
});
到
} else if (typeof window === 'object') {
/******** otherwise just pollute our global namespace ********/
window.GeographicLib = geo;
}
});
,然后您的 main.qml 就可以正常工作。
答案 1 :(得分:1)
您正在正确导入javascript文件。
来自doc:
QML提供了专门用于编写QML的JavaScript宿主环境。 应用程序。该环境不同于主机环境 由浏览器或服务器端JavaScript环境(例如 Node.js。例如, QML不提供窗口对象或DOM 在浏览器环境中常见的API。