Passed
Push — master ( 55b634...2bb861 )
by Tomasz
08:42
created

MapOpenLayers::htmlShowtime()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 2
1
<?php
2
3
/*
4
 * ******************************************************************************
5
 * Copyright 2011-2017 DANTE Ltd. and GÉANT on behalf of the GN3, GN3+, GN4-1 
6
 * and GN4-2 consortia
7
 *
8
 * License: see the web/copyright.php file in the file structure
9
 * ******************************************************************************
10
 */
11
12
namespace web\lib\admin;
13
14
require_once(dirname(dirname(dirname(dirname(__FILE__)))) . "/config/_config.php");
15
16
/**
17
 * This class provides map display functionality
18
 * 
19
 * @author Stefan Winter <[email protected]>
20
 */
21
class MapOpenLayers extends AbstractMap {
22
23
    public function __construct($inst, $readonly) {
24
        parent::__construct($inst, $readonly);
25
        return $this;
26
    }
27
    
28
    public function htmlHeadCode() {
29
        $cat = new \core\CAT();
30
        return "
31
        <link href='../external/OpenLayers/ol.css' rel='stylesheet' type='text/css'>
32
        <script src='../external/OpenLayers/ol.js'></script>
33
        <script>
34
        var addressService = 'https://nominatim.openstreetmap.org/search'; // the address search service
35
        var map; // the main map
36
        var markersArray = new Array(); // holds  all saved locations
37
        var extent; // the boundng box for locations
38
        var selectedMarker; // used to pass information about market to be identified
39
        var jmarkers; // set in the sorrounding PHP script as a json array to pass saved locations
40
        var markersSource = new ol.source.Vector(); // the vector source for locations
41
        var tmpSource = new ol.source.Vector(); // the vector source for temporaty markers
42
        var icon = new ol.style.Icon({ // the main location icon
43
            opacity: 1,
44
            src: '../resources/images/icons/location_marker.png'
45
        });
46
47
        var icon_selected = new ol.style.Icon({ // the main icon highlighted
48
            opacity: 1,
49
            src: '../resources/images/icons/location_marker_highlighted.png'
50
        });        
51
52
        var circle =  new ol.style.Circle({ // the temporatu icon
53
          radius: 10,
54
          stroke: new ol.style.Stroke({
55
            color: 'white',
56
            width: 2
57
          }),
58
          fill: new ol.style.Fill({
59
            color: 'green'
60
          })
61
        });
62
        
63
// use HTML5 geolocation
64
        function locateMe() {
65
            $('#address').val(\"" . _("locating") . "\");
66
            navigator.geolocation.getCurrentPosition(locate_succes,locate_fail,{maximumAge:3600000, timeout:5000});
67
        }
68
        
69
// on geolocation success set variables and show the temporaty marker
70
        function locate_succes(p) {
71
            $('#address').val('');
72
            $('#geo_long').val(p.coords.longitude);
73
            $('#geo_lat').val(p.coords.latitude);
74
            showTmpPointer(p.coords.longitude, p.coords.latitude);
75
        }
76
        
77
//geolocation failure
78
        function locate_fail(p) {
79
            $('#address').val('');
80
            alert('failure: '+p.message);
81
        }
82
        
83
// highlight a saved location pointed by the index
84
        function show_location(j) {
85
            m = markersArray[j];
86
            selectedMarker = j;
87
            m.setStyle(new ol.style.Style({image: icon_selected}));
88
            setTimeout('clear_icon(selectedMarker)', 1000);
89
        }
90
        
91
// remove location highlighting
92
        function clear_icon(j) {
93
            m = markersArray[j];
94
            m.setStyle(new ol.style.Style({image: icon}));
95
        }
96
97
// used to set locations icons
98
        function markersStyle(feature) {
99
            var style = new ol.style.Style({
100
                image: icon});
101
            return [style];
102
        }
103
        
104
// devine the markers layer
105
        var markersLayer = new ol.layer.Vector({
106
            source: markersSource,
107
            style: markersStyle
108
        });
109
        
110
// used to set temorary icons
111
        function tmpStyle(feature) {
112
            var style = new ol.style.Style({
113
                image: circle});
114
            return [style];
115
        }
116
// the temporary layer        
117
        var tmpLayer = new ol.layer.Vector({
118
            source: tmpSource,
119
            style: tmpStyle
120
        });
121
                
122
// Declare a Tile layer with an OSM source
123
        var osmLayer = new ol.layer.Tile({
124
            source: new ol.source.OSM()
125
        });
126
        
127
// set the markers for saved locations
128
        function addMarkers(jm) {
129
            locations = JSON.parse(jm);
130
            var locArray = new Array();
131
            var i = 0;
132
            var loc;
133
            var marker;
134
            for (i = 0; i < locations.length; i++) {
135
                loc = ol.proj.transform([Number(locations[i].lon), Number(locations[i].lat)], 'EPSG:4326', 'EPSG:3857');
136
                marker = new ol.Feature({geometry: new ol.geom.Point(loc)});
137
                markersSource.addFeature(marker);
138
                markersArray.push(marker);
139
                locArray.push(loc);
140
            }
141
            extent = ol.extent.boundingExtent(locArray);
142
        }
143
        
144
// set and display a temporary pointer clearing any old ones first
145
        function showTmpPointer(lon, lat) {
146
            tmpSource.clear()
147
            loc = ol.proj.transform([Number(lon), Number(lat)], 'EPSG:4326', 'EPSG:3857');
148
            marker = new ol.Feature({geometry: new ol.geom.Point(loc)});
149
            tmpSource.addFeature(marker);
150
            view = map.getView();
151
            view.setCenter(loc);
152
            view.setZoom(16);
153
        }
154
155
// the main map display funtion
156
        function generateMap(mapName) {
157
        // Instanciate a Map, set the object target to the map DOM id
158
            map = new ol.Map({
159
              controls: ol.control.defaults().extend([
160
    new ol.control.FullScreen()
161
  ]),
162
                target: mapName
163
            });
164
            var view = new ol.View();
165
            map.addLayer(osmLayer);
166
            map.addLayer(markersLayer);
167
            map.addLayer(tmpLayer);
168
            if (jmarkers !== undefined) { // no locations saved
169
                addMarkers(jmarkers, markersSource);
170
                view.setMaxZoom(14);
171
                view.fit(extent, {padding: [10, 0, 10, 0]});
172
                map.setView(view);
173
                view.fit(extent, {padding: [10, 0, 10, 0]});
174
            } else {
175
                view.setCenter([0,0]);
176
                locate_country('" . $cat->knownFederations[strtoupper($this->fedName)] . "'); // use the federation code to locate the country
177
                map.setView(view);
178
            }
179
            view.setMaxZoom(20);
180
        } 
181
        
182
// get the country center from the location service
183
        function locate_country(country) {
184
            $.get(addressService, {format: 'json', country: country, addressdetails: 0}, function(data) {
185
                if (data[0] === undefined) {
186
                    alert('Sorry, this error in locating your country should not have happened, please report it.');
187
                    return;
188
                }
189
                showTmpPointer(data[0].lon, data[0].lat);
190
                map.getView().setZoom(7);
191
            }, 'json');
192
        }
193
194
// get the location form the geocodig service
195
        function getAddressLocation() {
196
            var city = $('#address').val();
197
            if(city == '') {
198
                alert(\"" . _("nothing entered in the address field") . "\");
199
                return false;
200
            }
201
            city = city.replace(/\s*,\s*/g,',+');
202
            city = city.replace(/ +/,'+');
203
            $.get(addressService+'?format=json&addressdetails=0&q='+city, '',  function(data) {
204
                if (data[0] === undefined) {
205
                    alert('" . _("Address not found, perhaps try another form.") . "');
206
                    return;
207
                }
208
                showTmpPointer(data[0].lon, data[0].lat);
209
                map.getView().setZoom(16);
210
                $('#geo_long').val(data[0].lon);
211
                $('#geo_lat').val(data[0].lat);
212
            }, 'json');
213
        }
214
        
215
        "  .
216
        '$(document).ready(function () {
217
            $(".location_button").click(function (event) {
218
                event.preventDefault();
219
                marker_index = $(this).attr("id").substr(11) - 1;
220
                show_location(marker_index);
221
            });
222
223
            $("#address").keypress(function (event) {
224
                if (event.which === 13) {
225
                    event.preventDefault();
226
                    getAddressLocation();
227
                }
228
229
            });
230
        });' .
231
        "</script>
232
        ";
233
    }
234
235
    public function htmlBodyCode() {
236
237
        return "";
238
    }
239
240
    public function htmlShowtime($wizard = FALSE, $additional = FALSE) {
241
        if ($this->readOnly) {
242
            return "<div id='map' class='locationmap'></div><script>generateMap('map')</script>";
243
        } else {
244
            return $this->htmlPreEdit($wizard, $additional) . $this->findLocationHtml() . "<div id='map' class='locationmap'></div><script>generateMap('map')</script>" . $this->htmlPostEdit(FALSE);
245
        }
246
    }
247
248
    public function bodyTagCode() {
249
        // your magic here
250
        return "";
251
    }
252
253
    public static function optionListDisplayCode($coords, $number) {
254
        return "<button id='location_b_" . $number . "' class='location_button'>" . _("Click to see location") . " $number</button>";
255
    }
256
    
257
    private function findLocationHtml() {
258
        return "<p>" . _("Address:") . " <input name='address' id='address' /><button type='button' onclick='getAddressLocation()'>" . _("Find address") . "</button> <button type='button' onclick='locateMe()'>" . _("Locate Me!") . "</button></p>";
259
    }
260
}
261