기본 콘텐츠로 건너뛰기

OpenLayers | 3. 실시간 내 위치, 내 좌표 추적 (GeoLocation)


OpenLayers | 3. 실시간 내 위치, 내 좌표 추적 (GeoLocation)

배경지도 : Google, Vworld, Naver, Daum(Kakao)

좌표계 : 경위도, 구글, UTM-K, 중부원점




다양한 배경지도 위에

내 위치(좌표), 속도, 방향, 고도를 추적하는

오픈레이어스(OpenLayers) GeoLocation 예제입니다.





1. 예제 결과(Example Result)


좌표 :
속도 :
방향 :
고도 :
좌표계 :
배경지도 :




2. 예제 소스(Example Source)



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
<html>
<head>
 
    <!-- jquery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
 
<!-- openlayers -->
<link rel="stylesheet" href="https://openlayers.org/en/v4.6.5/css/ol.css" type="text/css">
<script src="https://openlayers.org/en/v4.6.5/build/ol.js"></script>
 
<!-- proj4js-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.6.2/proj4.js"></script>
 
    <style>
        body {
            margin: 0;
        }
        .map {
            width: 100%;
            height: 100%;
            position: relative;
        }
        #location {
            position: absolute;
            width: 100%;
            /* right: 10px; */
            bottom: 0px;
              padding: 10px;
              box-sizing: border-box;
            z-index: 1;
              background-color: rgba(0,0,0,0.6);
              font-size: 12px;
        }
  
          #location span, #location label {
            color: #ffffff;
              font-size: 12px;
        }
 
    </style>
 
    <script>
    
        // dom ready
        $(document).ready(function() {
            init();
        });
    
        function init() {
 
            // 좌표계 설정
            initProj();
        
            // map 생성
            var map = new ol.Map({
                target: 'map',                          // Map 생성할 div id
                view: new ol.View({
                    center: [543000004300000],        // 초기 지도 위치 좌표
                    zoom: 8                             // 초기 지도 위치 줌레벨
                }),
                logo: false,
                controls: ol.control.defaults({
                    attribution: false
                }),
            });
 
            // 풀스크린 컨트롤러
            map.addControl(new ol.control.FullScreen());
            
            // 배경지도 레이어 추가
            addBaseLayer(map);
 
            // 배경지도 선택 select
            initBaseLayerSelect(map);
 
            // Geolocation
            initGeolocation(map);;
 
        }
 
        function initProj() {
 
            // 경위도
            proj4.defs('EPSG:4326''+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs');
 
            // google 좌표계
            proj4.defs('EPSG:3857''+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs');
 
            // UTM-K 좌표계
            proj4.defs('EPSG:5179''+proj=tmerc +lat_0=38 +lon_0=127.5 +k=0.9996 +x_0=1000000 +y_0=2000000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs');
 
            // 중부원점(Bessel)
            proj4.defs('EPSG:2097''+proj=tmerc +lat_0=38 +lon_0=127 +k=1 +x_0=200000 +y_0=500000 +ellps=bessel +units=m +no_defs');
 
            // 보정된 중부원점(Bessel)
            proj4.defs('EPSG:5174''+proj=tmerc +lat_0=38 +lon_0=127.0028902777778 +k=1 +x_0=200000 +y_0=500000 +ellps=bessel +units=m +no_defs +towgs84=-115.80,474.99,674.11,1.16,-2.31,-1.63,6.43');
 
            // 중부원점(GRS80) [200,000 500,000]
            proj4.defs('EPSG:5181''+proj=tmerc +lat_0=38 +lon_0=127 +k=1 +x_0=200000 +y_0=500000 +ellps=GRS80 +units=m +no_defs');
 
            // 중부원점(GRS80) [200,000 600,000]
            proj4.defs('EPSG:5186''+proj=tmerc +lat_0=38 +lon_0=127 +k=1 +x_0=200000 +y_0=600000 +ellps=GRS80 +units=m +no_defs');
 
        }
 
        function addBaseLayer(map) {
 
            // ------------------------------
            // google layers
            // ------------------------------
            // google road
            var googleRoadLayer = new ol.layer.Tile({
                source: new ol.source.XYZ({
                    projection : 'EPSG:3857',
                    url : 'https://mt0.google.com/vt/lyrs=m&hl=en&x={x}&y={y}&z={z}',
                    crossOrigin: 'anonymous'
                }),
                id: 'google_road',
                visible: false
            });
            map.addLayer(googleRoadLayer);
 
            // google terrain
            var googleTerrainLayer = new ol.layer.Tile({
                source: new ol.source.XYZ({
                    projection : 'EPSG:3857',
                    url : 'https://mt0.google.com/vt/lyrs=p&hl=en&x={x}&y={y}&z={z}',
                    crossOrigin: 'anonymous'
                }),
                id: 'google_terrain',
                visible: false
            });
            map.addLayer(googleTerrainLayer);
 
            // google altered road
            var googleAlteredRoadLayer = new ol.layer.Tile({
                source: new ol.source.XYZ({
                    projection : 'EPSG:3857',
                    url : 'https://mt0.google.com/vt/lyrs=r&hl=en&x={x}&y={y}&z={z}',
                    crossOrigin: 'anonymous'
                }),
                id: 'google_altered_road',
                visible: false
            });
            map.addLayer(googleAlteredRoadLayer);
 
            // google satellite
            var googleSatelliteLayer = new ol.layer.Tile({
                source: new ol.source.XYZ({
                    projection : 'EPSG:3857',
                    url : 'https://mt0.google.com/vt/lyrs=s&hl=en&x={x}&y={y}&z={z}',
                    crossOrigin: 'anonymous'
                }),
                id: 'google_satellite',
                visible: false
            });
            map.addLayer(googleSatelliteLayer);
 
            // google terrain only
            var googleTerrainOnlyLayer = new ol.layer.Tile({
                source: new ol.source.XYZ({
                    projection : 'EPSG:3857',
                    url : 'https://mt0.google.com/vt/lyrs=t&hl=en&x={x}&y={y}&z={z}',
                    crossOrigin: 'anonymous'
                }),
                id: 'google_terrain_only',
                visible: false
            });
            map.addLayer(googleTerrainOnlyLayer);
 
            // google hybrid
            var googleHybridLayer = new ol.layer.Tile({
                source: new ol.source.XYZ({
                    projection : 'EPSG:3857',
                    url : 'https://mt0.google.com/vt/lyrs=y&hl=en&x={x}&y={y}&z={z}',
                    crossOrigin: 'anonymous'
                }),
                id: 'google_hybrid',
                visible: false
            });
            map.addLayer(googleHybridLayer);
 
 
            // ------------------------------
            // OSM(OpenStreetMap)
            // ------------------------------
            // osm standard
            // var osmStandardLayer = new ol.layer.Tile({
            //     source: new ol.source.OSM()
            // });
            // map.addLayer(osmStandardLayer);
            var osmStandardLayer = new ol.layer.Tile({
                source: new ol.source.XYZ({
                    projection : 'EPSG:3857',
                    url : 'https://{a-c}.tile.openstreetmap.org/{z}/{x}/{y}.png',
                    crossOrigin: 'anonymous'
                }),
                id: 'osm_standard',
                visible: false
            });
            map.addLayer(osmStandardLayer);
 
            // osm cyclosm
            var osmCyclosmLayer = new ol.layer.Tile({
                source: new ol.source.XYZ({
                    projection : 'EPSG:3857',
                    url : 'https://a.tile-cyclosm.openstreetmap.fr/cyclosm/{z}/{x}/{y}.png',
                    crossOrigin: 'anonymous'
                }),
                id: 'osm_cyclosm',
                visible: false
            });
            map.addLayer(osmCyclosmLayer);
 
            // osm humanitarian
            var osmHumanitarianLayer = new ol.layer.Tile({
                source: new ol.source.XYZ({
                    projection : 'EPSG:3857',
                    url : 'https://tile-{a-c}.openstreetmap.fr/hot/{z}/{x}/{y}.png',
                    crossOrigin: 'anonymous'
                }),
                id: 'osm_humanitarian',
                visible: false
            });
            map.addLayer(osmHumanitarianLayer);
 
 
            // ------------------------------
            // vworld layers
            // ------------------------------
            // vworld base
            var vworldBaseLayer = new ol.layer.Tile({
                source: new ol.source.XYZ({
                    projection : 'EPSG:3857',
                    url : 'https://xdworld.vworld.kr/2d/Base/service/{z}/{x}/{y}.png',
                    crossOrigin: 'anonymous'
                }),
                id: 'vworld_base',
                visible: false
            });
            map.addLayer(vworldBaseLayer);
 
            // vworld satellite
            var vworldSatelliteLayer = new ol.layer.Tile({
                source: new ol.source.XYZ({
                    projection : 'EPSG:3857',
                    url : 'https://xdworld.vworld.kr/2d/Satellite/service/{z}/{x}/{y}.jpeg',
                    crossOrigin: 'anonymous'
                }),
                id: 'vworld_satellite',
                visible: false
            });
            map.addLayer(vworldSatelliteLayer);
 
            // vworld hybrid
            var vworldHybridLayer = new ol.layer.Tile({
                source: new ol.source.XYZ({
                    projection : 'EPSG:3857',
                    url : 'https://xdworld.vworld.kr/2d/Hybrid/service/{z}/{x}/{y}.png',
                    crossOrigin: 'anonymous'
                }),
                id: 'vworld_hybrid',
                visible: false
            });
            map.addLayer(vworldHybridLayer);
 
            // vworld gray
            var vworldGrayLayer = new ol.layer.Tile({
                source: new ol.source.XYZ({
                    projection : 'EPSG:3857',
                    url : 'https://xdworld.vworld.kr/2d/gray/service/{z}/{x}/{y}.png',
                    crossOrigin: 'anonymous'
                }),
                id: 'vworld_gray',
                visible: false
            });
            map.addLayer(vworldGrayLayer);
 
            // vworld_midnight
            var vworldMidnightLayer = new ol.layer.Tile({
                source: new ol.source.XYZ({
                    projection : 'EPSG:3857',
                    url : 'https://xdworld.vworld.kr/2d/midnight/service/{z}/{x}/{y}.png',
                    crossOrigin: 'anonymous'
                }),
                id: 'vworld_midnight',
                visible: false
            });
            map.addLayer(vworldMidnightLayer);
 
 
            // ------------------------------
            // naver layers
            // ------------------------------
            // naver base
            var naverBaseLayer = new ol.layer.Tile({
                source: new ol.source.XYZ({
                    projection : 'EPSG:3857',
                    url : 'https://map.pstatic.net/nrb/styles/basic/1646972073/{z}/{x}/{y}@2x.png',
                    tilePixelRatio: 2,              // 타일사이즈 512일때 해상도 비율
                    crossOrigin: 'anonymous'
                }),
                id: 'naver_base',
                visible: false
            });
            map.addLayer(naverBaseLayer);
 
            // naver satellite
            var naverSatelliteLayer = new ol.layer.Tile({
                source: new ol.source.XYZ({
                    projection : 'EPSG:3857',
                    url : 'https://map.pstatic.net/nrb/styles/satellite/1646972073/{z}/{x}/{y}@2x.png',
                    tilePixelRatio: 2,              // 타일사이즈 512일때 해상도 비율
                    crossOrigin: 'anonymous'
                }),
                id: 'naver_satellite',
                visible: false
            });
            map.addLayer(naverSatelliteLayer);
 
            // naver terrain
            var naverTerrainLayer = new ol.layer.Tile({
                source: new ol.source.XYZ({
                    projection : 'EPSG:3857',
                    url : 'https://map.pstatic.net/nrb/styles/terrain/1646972073/{z}/{x}/{y}@2x.png',
                    tilePixelRatio: 2,              // 타일사이즈 512일때 해상도 비율
                    crossOrigin: 'anonymous'
                }),
                id: 'naver_terrain',
                visible: false
            });
            map.addLayer(naverTerrainLayer);
 
            // ------------------------------
            // daum(kakao) layers
            // ------------------------------
            var daumTileGrid = new ol.tilegrid.TileGrid({
                extent : [(-30000-524288), (-60000-524288), (494288+524288), (988576+524288)],
                tileSize : 256,
                resolutions : [40962048102451225612864321684210.50.25], 
                minZoom : 1
            });
 
            function getDaumTileUrlFunction(type) {
 
                var tileUrlFunction = function(tileCoord, pixelRatio, projection) {
 
                    var res = this.getTileGrid().getResolutions();
                    var sVal = res[tileCoord[0]];
                    
                    var yLength = 988576 - (-60000+ 524288 + 524288;
                    var yTile = yLength / (sVal * this.getTileGrid().getTileSize());
 
                    var tileGap = Math.pow(2, (tileCoord[0-1));
                    yTile = yTile - tileGap;
                    
                    var xTile = tileCoord[1- tileGap;
            
                    if (type == 'base') {
                        return 'https://map' + Math.floor( (Math.random() * (4 - 1 + 1)) + 1 ) + '.daumcdn.net/map_2d_hd/2111ydg/L' + (15 - tileCoord[0]) + '/' + (yTile + tileCoord[2]) + '/' + xTile + '.png';
                    } else if (type == 'satellite') {
                        return 'https://map' + Math.floor( (Math.random() * (4 - 1 + 1)) + 1 ) + '.daumcdn.net/map_skyview_hd/L' + (15 - tileCoord[0]) + '/' + (yTile + tileCoord[2]) + '/' + xTile + '.jpg';
                    } else if (type == 'hybrid') {
                        return 'https://map' + Math.floor( (Math.random() * (4 - 1 + 1)) + 1 ) + '.daumcdn.net/map_hybrid_hd/2111ydg/L' + (15 - tileCoord[0]) + '/' + (yTile + tileCoord[2]) + '/' + xTile + '.png';
                    }
 
                };
 
                return tileUrlFunction;
 
            }
 
            // daum base
            var daumBaseLayer = new ol.layer.Tile({
                source: new ol.source.XYZ({
                    projection : 'EPSG:5181',
                    tileGrid: daumTileGrid,
                    tileUrlFunction: getDaumTileUrlFunction('base'),
                    tilePixelRatio: 2,              // 타일사이즈 512일때 해상도 비율
                }),
                id: 'daum_base',
                visible: false
            });
            map.addLayer(daumBaseLayer);
 
            // daum satellite
            var daumSatelliteLayer = new ol.layer.Tile({
                source: new ol.source.XYZ({
                    projection : 'EPSG:5181',
                    tileGrid: daumTileGrid,
                    tileUrlFunction: getDaumTileUrlFunction('satellite'),
                    tilePixelRatio: 2,              // 타일사이즈 512일때 해상도 비율
                }),
                id: 'daum_satellite',
                visible: false
            });
            map.addLayer(daumSatelliteLayer);
 
            // daum hybrid
            var daumHybridLayer = new ol.layer.Tile({
                source: new ol.source.XYZ({
                    projection : 'EPSG:5181',
                    tileGrid: daumTileGrid,
                    tileUrlFunction: getDaumTileUrlFunction('hybrid'),
                    tilePixelRatio: 2,              // 타일사이즈 512일때 해상도 비율
                }),
                id: 'daum_hybrid',
                visible: false
            });
            map.addLayer(daumHybridLayer);
            
 
        }
 
        function initBaseLayerSelect(map) {
 
            // add select option
            var html = '';
            $.each(map.getLayers().getArray(), function(i, v) {
                html += '<option value="' + v.get('id'+ '">' + v.get('id'+ '</option>';
            });
            $('#baseLayer').append(html);
 
            // select event
            $('#baseLayer').change(function() {
 
                var layerId = $(this).val();
                $.each(map.getLayers().getArray(), function(i, v) {
                    if (layerId == v.get('id')) {
                        v.setVisible(true);
                    } else {
                        v.setVisible(false);
                    }
                });
 
            });
 
            // 초기값
            $('#baseLayer').val('daum_base').trigger('change');
 
        }
 
          // 지오로케이션
        function initGeolocation(map) {
          
              // [내위치로 이동] 버튼 이벤트
            $('#myLocation').click(function() {
                var pos = geolocation.getPosition();
                if (pos == null) {
                    return;
                }
                map.getView().animate({
                    center: pos,
                    zoom: 18,
                    duration: 1000
                });
            });
 
            // 좌표계 변경 이벤트
            $('#coordinate').change(function() {
               $('#position').text('');
               geolocation.changed();
            });
 
            var geolocation = new ol.Geolocation({
                tracking: true,
                projection: map.getView().getProjection()
            });
 
            window.geolocation = geolocation;
 
            function el(id) {
                return document.getElementById(id);
            }
 
            // 좌표 변경 오픈레이어스 이벤트
            geolocation.on('change'function() {
 
                var pos = geolocation.getPosition();
              
                  if($('#isTrakingLocation').is(':checked'== true) {
                  if (pos != null) {
                    //map.getView().setCenter(pos);
                    map.getView().animate({
                      center: pos,
                      duration: 500
                    });
                  }
                }
              
                if (map.getView().getProjection().getCode() != $('#coordinate').val()) {
                    pos = ol.proj.transform(pos, map.getView().getProjection().getCode(), $('#coordinate').val())
                }
         
                el('position').innerText = pos;
                // el('accuracy').innerText = geolocation.getAccuracy() + '[m]';
                el('altitude').innerText = geolocation.getAltitude() == null ? 'loading' : geolocation.getAltitude() + '[m]';
                // el('altitudeAccuracy').innerText = geolocation.getAltitudeAccuracy() + '[m]';
                // el('heading').innerText = geolocation.getHeading() == null ? 'loading' : geolocation.getHeading() + '[rad]';
                  el('heading').innerText = geolocation.getHeading() == null ? 'loading' : (geolocation.getHeading() * 360 / (Math.PI * 2)) + '[°]';
              
                el('speed').innerText = geolocation.getSpeed() == null ? 'loading' : geolocation.getSpeed() + '[m/s]';
            });
 
            var accuracyFeature = new ol.Feature();
            geolocation.on('change:accuracyGeometry'function() {
                accuracyFeature.setGeometry(geolocation.getAccuracyGeometry());
            });
 
              // 포인트 객체
            var positionFeature = new ol.Feature();
            positionFeature.setStyle(new ol.style.Style({
                image: new ol.style.Circle({
                  radius: 6,
                  fill: new ol.style.Fill({
                      color: '#3399CC'
                  }),
                  stroke: new ol.style.Stroke({
                      color: '#fff',
                      width: 2
                  })
                })
            }));
 
            geolocation.on('change:position'function() {
                var coordinates = geolocation.getPosition();
                positionFeature.setGeometry(coordinates ? new ol.geom.Point(coordinates) : null);
            });
 
            new ol.layer.Vector({
                map: map,
                source: new ol.source.Vector({
                features: [accuracyFeature, positionFeature]
                })
            });
 
        }
    
    </script>
 
</head>
<body>
 
    <div id="map" class="map">
    <div id="location">
        <div>
            <span>좌표 : <code id="position"></code></span>
        </div>
        <div>
            <span>속도 : <code id="speed"></code></span>
        </div>
        <div>
            <span>방향 : <code id="heading"></code></span>
        </div>
        <div>
            <span>고도 : <code id="altitude"></code></span>
        </div>
        <div>
            <span>좌표계 : </span>
            <select id="coordinate">
                <option value="EPSG:4326" selected>EPSG:4326 | 경위도</option>
                <option value="EPSG:3857">EPSG:3857 | Google 좌표계</option>
                <option value="EPSG:5179">EPSG:5179 | UTM-K</option>
                <option value="EPSG:2097">EPSG:2097 | 중부원점(Bessel)</option>
                <option value="EPSG:5174">EPSG:5174 | 보정된 중부원점(Bessel)</option>
                <option value="EPSG:5181">EPSG:5181 | 중부원점(GRS80) [20만, 50만]</option>
                <option value="EPSG:5186">EPSG:5186 | 중부원점(GRS80) [20만,  60만]</option>
            </select>
        </div>
        <div>
            <span>배경지도 : </span><select id="baseLayer"></select>
        </div>
        <div>
            <button id="myLocation">내 위치로 이동</button>
            <label style="margin-left: 5px;"><input type="checkbox" id="isTrakingLocation"> 내 위치로 자동 이동</label>
        </div>
    </div>
 
</body>
</html>






댓글