UNPKG

2.33 kBJavaScriptView Raw
1goog.require('ol.Feature');
2goog.require('ol.Geolocation');
3goog.require('ol.Map');
4goog.require('ol.View');
5goog.require('ol.control');
6goog.require('ol.geom.Point');
7goog.require('ol.layer.Tile');
8goog.require('ol.layer.Vector');
9goog.require('ol.source.OSM');
10goog.require('ol.source.Vector');
11goog.require('ol.style.Circle');
12goog.require('ol.style.Fill');
13goog.require('ol.style.Stroke');
14goog.require('ol.style.Style');
15
16var view = new ol.View({
17 center: [0, 0],
18 zoom: 2
19});
20
21var map = new ol.Map({
22 layers: [
23 new ol.layer.Tile({
24 source: new ol.source.OSM()
25 })
26 ],
27 target: 'map',
28 controls: ol.control.defaults({
29 attributionOptions: {
30 collapsible: false
31 }
32 }),
33 view: view
34});
35
36var geolocation = new ol.Geolocation({
37 projection: view.getProjection()
38});
39
40function el(id) {
41 return document.getElementById(id);
42}
43
44el('track').addEventListener('change', function() {
45 geolocation.setTracking(this.checked);
46});
47
48// update the HTML page when the position changes.
49geolocation.on('change', function() {
50 el('accuracy').innerText = geolocation.getAccuracy() + ' [m]';
51 el('altitude').innerText = geolocation.getAltitude() + ' [m]';
52 el('altitudeAccuracy').innerText = geolocation.getAltitudeAccuracy() + ' [m]';
53 el('heading').innerText = geolocation.getHeading() + ' [rad]';
54 el('speed').innerText = geolocation.getSpeed() + ' [m/s]';
55});
56
57// handle geolocation error.
58geolocation.on('error', function(error) {
59 var info = document.getElementById('info');
60 info.innerHTML = error.message;
61 info.style.display = '';
62});
63
64var accuracyFeature = new ol.Feature();
65geolocation.on('change:accuracyGeometry', function() {
66 accuracyFeature.setGeometry(geolocation.getAccuracyGeometry());
67});
68
69var positionFeature = new ol.Feature();
70positionFeature.setStyle(new ol.style.Style({
71 image: new ol.style.Circle({
72 radius: 6,
73 fill: new ol.style.Fill({
74 color: '#3399CC'
75 }),
76 stroke: new ol.style.Stroke({
77 color: '#fff',
78 width: 2
79 })
80 })
81}));
82
83geolocation.on('change:position', function() {
84 var coordinates = geolocation.getPosition();
85 positionFeature.setGeometry(coordinates ?
86 new ol.geom.Point(coordinates) : null);
87});
88
89new ol.layer.Vector({
90 map: map,
91 source: new ol.source.Vector({
92 features: [accuracyFeature, positionFeature]
93 })
94});