Geolocation API
Максим Воронцов
Geolocation API
if (navigator.geolocation) {
// ...
} else {
alert('Geolocation API не поддерживается');
}
Geolocation API
navigator.geolocation.getCurrentPosition(
function (position) { ... },
function (error) { ... },
options
);
var options = {
enableHighAccuracy: true,
maximumAge: 50000,
timeout: 10000
};
var id = navigator.geolocation.watchPosition(...);
navigator.geolocation.clearWatch(id);
{
coords: {
accuracy: 45,
altitude: null,
altitudeAccuracy: null,
heading: null,
latitude: 56.783005499999994,
longitude: 60.54139849999999,
speed: null
},
timestamp: 1459788138892
}
Geolocation API
- GPS - Global Positioning System
- Google's Geolocation Service
Chrome, Firefox, Opera
- skyhookwireless.com
Safari
- Microsoft Location Service
Internet Explorer, Edge
Для чего?
- Доступ к файлам из файловой системы
- Получение контента файла без отправки на сервер
- Работа с файлами как с бинарными данными
File APIs
- Blob - file-like объект, позволяет работать с
бинарными данными
- File - собственно файл, основан на Blob
- FileList - набор объектов типа File
- FileReader - позволяет осуществлять асинхронное чтение
объектов типа Blob или File и получать доступ к их контенту
Где использовать?
- Online-редакторы
- Превью загруженных файлов
- Создание файлов различных форматов прямо в браузере
- Загрузка изображений на canvas и работа с ними
File APIs
if (window.Blob && window.File &&
window.FileList && window.FileReader) {
// File APIs полностью поддерживаются
} else {
// File APIs поддерживаются не полностью
}
Blob: Binary Large Object
Blob(blobParts, options)
var blob = new Blob(['abc', 'def'], options);
var blob = new Blob([otherBlob1, otherBlob2], options);
var blob = new Blob(['abc', otherBlob], options);
var options = {
type: 'plain/text',
endings: 'native' // default: 'transparent'
};
Blob: Binary Large Object
blob.size; // Размер в байтах
blob.type; // MIME-type
blob.slice(start, end, contentType);
blob.close();
Blob URLs
var blob = new Blob(['abc'], { type: 'plain/text' });
if (window.URL) {
var url = window.URL.createObjectURL(blob);
// blob:d3958f5c-0777-0845-9dcf-2cb28783acaf
window.URL.revokeObjectURL(url);
} else {
// Blob URLs не поддерживаются
}
Пример: Скачивание файла
<textarea id="text"></textarea>
<button id="button">Получить ссылку</button>
<a id="link" download="text.txt">Скачать</a>
Пример: Скачивание файла
var textarea = document.getElementById('text');
var button = document.getElementById('button');
var link = document.getElementById('link');
button.addEventListener('click', function () {
var text = textarea.value;
var blob = new Blob([text], { type: 'plain/text' });
var url = window.URL.createObjectURL(blob);
link.href = url;
});
Создание файлов различных форматов
jsZip
var zip = new JSZip();
zip.file("Hello.txt", "Hello World\n");
var imagesFoler = zip.folder("images");
imagesFolder.file("smile.gif", imgData, {base64: true});
zip
.generateAsync({type:"blob"})
.then(function(blob) {
// ...
});
Создание файлов различных форматов
jsPDF
var doc = new jsPDF();
doc.text(20, 20, 'Hello world!');
doc.text(20, 30, 'This is client-side Javascript');
doc.addPage();
doc.text(20, 20, 'Do you like that?');
Загрузка файлов: <input>
<input type="file" multiple>
<input type="file" multiple accept="application/pdf">
<input type="file" multiple accept="image/png,image/jpeg">
<input type="file" multiple accept="image/*">
<input type="file" multiple accept="video/*">
<input type="file" multiple accept="audio/*">
Загрузка файлов: <input>
var input = document.getElementById('input');
input.addEventListener('change', function () {
var files = input.files; // FileList
files.length;
files[0];
files.item(0);
});
File
{
lastModified: 1461053555000,
lastModifiedDate: 'Date 2016-04-18T09:23:08.000Z',
name: 'img.png',
size: 8057,
type: 'image/png'
}
Загрузка файлов: Drag and Drop
<div id="drop-zone"></div>
<div id="names"></div>
var dropZone = document.getElementById('drop-zone');
var names = document.getElementById('names');
dropZone.addEventListener('dragover', function (event) {
event.preventDefault();
event.dataTransfer.dropEffect = 'copy';
});
Загрузка файлов: Drag and Drop
dropZone.addEventListener('drop', function (event) {
event.preventDefault();
var files = event.dataTransfer.files;
var output = [];
for (var i = 0; i < files.length; i++) {
output.push('<li>' + files[i].name + '</li>');
}
names.innerHTML = '<ol>' + output.join('') + '</ol>';
});
Подробнее про Drag and Drop
Загрузка файлов: Drag and Drop
Чтение файла
var reader = new FileReader();
reader.readAsArrayBuffer(file)
reader.readAsBinaryString(file)
reader.readAsDataURL(file)
reader.readAsText(file)
reader.abort()
Чтение файла
reader.onerror
reader.onloadstart
reader.onloadend // даже в случаее неудачной загрузки
reader.onload // только в случае успеха
reader.onprogress
reader.error
reader.readyState // EMPTY - 0, LOADING - 1, DONE - 2
reader.result
Пример: Загрузка файлов
<input id="input" type="file" accept="image/*">
<div id="images"></div>
Пример: Загрузка файлов
var input = document.getElementById('input');
var images = document.getElementById('images');
input.addEventListener('change', function () {
var image = input.files[0];
var reader = new FileReader();
reader.readAsDataURL(image);
reader.addEventListener('load', function () {
var img = document.createElement('img');
img.src = reader.result;
images.appendChild(img);
});
});