【发布时间】:2016-10-28 19:59:18
【问题描述】:
我一直在努力开发一些在 javascript 中使用异步函数的代码。代码在 Mozilla 中运行良好,但 Chrome 的 console.log 没有显示任何内容......并且没有记录任何错误。
代码处理图像对象数组,并使用 EXIF-js 库中的异步函数从数组中的地理标记图像中检索 GPS 坐标。所有这些代码都可以正常工作。
使用回调,我可以在 Mozilla 中控制台记录位置坐标,但是当我在 Chrome 中运行相同的代码时,我什么也得不到。
这是一个执行时间/速度问题吗(FF 可能更慢,因此有更多时间来生成要显示的值?)..我想我通过使用回调函数来避免这种情况。
对于方向,这是我理解它的工作方式(从下往上阅读):
- 我声明了图像数组。它不包含 GPS 数据
- 我运行 getLocations(注意“s”),将图像数组作为参数传递给函数。
- getLocations 遍历数组,创建一个图像对象以传递给 getLocation(单数)函数。该调用包括对结果的回调。
- getLocation 在图像上运行 EXIF.getData,通过 convertDMtoDD 进行一些转换后,加载带有纬度和经度的位置数组。
- getLocation 然后调用回调,将位置作为参数传递。
- console.log 记录这些值,但前提是我使用 Mozilla、FF。 Chrome 什么都不显示?!
function convertDMtoDD(coordinates, direction) {
//convert the decimal minutes coordinate array to decimal degrees
//set the sign based on direction where "S" or "E" is negative
gpsdegrees = (coordinates[0]);
gpsminutes = (coordinates[1]);
leftminutes = Math.floor(gpsminutes);
rightminutes = (gpsminutes - leftminutes) / 60;
leftminutes = leftminutes / 60;
rightminutes = leftminutes + rightminutes;
degdecimal = (gpsdegrees + rightminutes).toFixed(6);
if (direction == "S" || direction == "W") {
degdecimal = 0 - degdecimal;
}
return degdecimal;
}
function getLocation(myimage, callback) {
//EXIF.getData in the EXIF.js library gets the EXIF data from the raw image DOM object
myimage.onload = EXIF.getData(myimage, function() {
//EXIF.getTag pulls the various data for each tag such as latitude, longitude, etc.
//lati and longi are arrays containing decimalminutes values; latd and longd are single values of either "N", "S", "W", or "E")
var lati = EXIF.getTag(this, "GPSLatitude");
var latd = EXIF.getTag(this, "GPSLatitudeRef");
var longi = EXIF.getTag(this, "GPSLongitude");
var longd = EXIF.getTag(this, "GPSLongitudeRef");
var location = [];
//convert data from decimal minutes to decimal degrees and set direction as neg or pos
location[0] = convertDMtoDD(lati, latd);
location[1] = convertDMtoDD(longi, longd);
callback(location);
});
}
var images = [
{
name: 'Chateau Coussay',
src: 'coussay.jpg'
}, {
name: 'Chateau Courlaine',
src: 'coulaine.jpg'
}, {
name: 'Chateau Sainte-Chapelle',
src: 'chapelle.jpg'
}
];
function getLocations(imagelist) {
for (var i = 0; i < imagelist.length; i++) {
var myimage = new Image(); //create image object to pass to the getLocation function
myimage.src = imagelist[i].src;
getLocation(myimage, function(location) {
console.log("latitude is " + location[0] + " longitude is " + location[1]);
});
}
}
getLocations(images);
【问题讨论】:
-
感谢重新格式化....还没有做太多,当我复制/粘贴到代码块时,我得到了很多奇怪的缩进......
标签: javascript asynchronous image-processing callback asynccallback