Files
openlayers/examples/geolocation.js
2018-04-24 09:06:30 -06:00

97 lines
2.5 KiB
JavaScript

import Feature from '../src/ol/Feature.js';
import Geolocation from '../src/ol/Geolocation.js';
import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import {defaults as defaultControls} from '../src/ol/control.js';
import Point from '../src/ol/geom/Point.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
import {OSM, Vector as VectorSource} from '../src/ol/source.js';
import CircleStyle from '../src/ol/style/Circle.js';
import Fill from '../src/ol/style/Fill.js';
import Stroke from '../src/ol/style/Stroke.js';
import Style from '../src/ol/style/Style.js';
const view = new View({
center: [0, 0],
zoom: 2
});
const map = new Map({
layers: [
new TileLayer({
source: new OSM()
})
],
target: 'map',
controls: defaultControls({
attributionOptions: {
collapsible: false
}
}),
view: view
});
const geolocation = new Geolocation({
// enableHighAccuracy must be set to true to have the heading value.
trackingOptions: {
enableHighAccuracy: true
},
projection: view.getProjection()
});
function el(id) {
return document.getElementById(id);
}
el('track').addEventListener('change', function() {
geolocation.setTracking(this.checked);
});
// update the HTML page when the position changes.
geolocation.on('change', function() {
el('accuracy').innerText = geolocation.getAccuracy() + ' [m]';
el('altitude').innerText = geolocation.getAltitude() + ' [m]';
el('altitudeAccuracy').innerText = geolocation.getAltitudeAccuracy() + ' [m]';
el('heading').innerText = geolocation.getHeading() + ' [rad]';
el('speed').innerText = geolocation.getSpeed() + ' [m/s]';
});
// handle geolocation error.
geolocation.on('error', function(error) {
const info = document.getElementById('info');
info.innerHTML = error.message;
info.style.display = '';
});
const accuracyFeature = new Feature();
geolocation.on('change:accuracyGeometry', function() {
accuracyFeature.setGeometry(geolocation.getAccuracyGeometry());
});
const positionFeature = new Feature();
positionFeature.setStyle(new Style({
image: new CircleStyle({
radius: 6,
fill: new Fill({
color: '#3399CC'
}),
stroke: new Stroke({
color: '#fff',
width: 2
})
})
}));
geolocation.on('change:position', function() {
const coordinates = geolocation.getPosition();
positionFeature.setGeometry(coordinates ?
new Point(coordinates) : null);
});
new VectorLayer({
map: map,
source: new VectorSource({
features: [accuracyFeature, positionFeature]
})
});