Passed
Push — master ( 12ba88...25e691 )
by Stefan
08:44
created

MapGoogle::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
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 MapGoogle 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 "<script type='text/javascript' src='https://maps.googleapis.com/maps/api/js?key=" . CONFIG['APPEARANCE']['google_maps_api_key'] . "'></script>
31
    <script type='text/javascript'>
32
        // some global variables;
33
        var center_lat=49.6114885608729;
34
        var center_lng=6.135778427124023;
35
        var zoom=15;
36
        var mode;
37
        var map;
38
        var marker;
39
        var geocoder;
40
        var icon;
41
        var icon_red;
42
        var center_map=true;
43
        var marks = [];
44
        var markers;
45
        var marker_index;
46
47
        /**
48
         * xml parser function
49
         * replaces a Google v2 builtin
50
         */
51
        function parse_xml(s) { 
52
            if (window.DOMParser)
53
            {
54
                parser=new DOMParser();
55
                xml=parser.parseFromString(s,'text/xml');
56
            }
57
            else // Internet Explorer
58
            {
59
                xml=new ActiveXObject('Microsoft.XMLDOM');
60
                xml.async=false;
61
                xml.loadXML(s);
62
            }
63
            return xml;
64
        }
65
66
67
        /**
68
         *  Loceate country center
69
         */
70
71
        function locate_country(country) {
72
            geocoder.geocode({'address':country},function(r,status) {
73
                if(status != google.maps.GeocoderStatus.OK) {
74
                    alert('Sorry, this error in locating your country should not have happened, please report it.');
75
                } else {
76
                    addMarker(r[0].geometry.location,0,r[0].geometry.bounds);
77
                }
78
            });
79
        }
80
81
        /**
82
         * Guess location based on ist name and country
83
         *
84
         */
85
        function locator_magic() {
86
            geocoder.geocode({'address':\"" . preg_replace("/\"/", "&quot;", $this->instName) . "\", 'region':\"" . strtolower($this->fedName) . "\"},
87
            function(r,status) {
88
                if(status != google.maps.GeocoderStatus.OK) {
89
                    locate_country(\"" . $cat->knownFederations[strtoupper($this->fedName)] . "\");
90
                } else {
91
                    var i;
92
                    for(i = 0; i < r.length; i++) {
93
                        Addr = getAddressElements(r[i].address_components);
94
                        if(Addr.country == \"" . strtoupper($this->fedName) . "\")
95
                        break;
96
                    }
97
                    if(Addr.country != \"" . strtoupper($this->fedName) . "\")
98
                    locate_country(\"" . $cat->knownFederations[strtoupper($this->fedName)] . "\");
99
                    else {
100
                        addMarker(r[i].geometry.location,15,null);
101
                    }
102
                }
103
            });
104
        }
105
106
        /**
107
         * click event listener
108
         */
109
        function markerClicked(m) {
110
            info_window.close();
111
            var t = \"" . _("This is location ") . "\"+m.info;
112
            info_window.setContent(t);
113
            info_window.setPosition(m.getPosition());
114
            info_window.open(map,m);
115
        }
116
117
        function getAddressElements(addr) {
118
            var A = new Object();
119
            var l1 ='';
120
            A.locality = '';
121
            A.country = '';
122
            for(i=0;i< addr.length;i++) {
123
                if(addr[i].types[0] == 'locality')
124
                    A.locality = addr[i].short_name;
125
                if(addr[i].types[0] == 'administrative_area_level_3' )
126
                    l1 = addr[i].short_name;
127
                if(addr[i].types[0] == 'country' ){
128
                    A.country = addr[i].short_name;
129
                    A.country_long = addr[i].long_name;
130
                }
131
            }
132
            if(A.locality == '')
133
                A.locality = l1;
134
            return(A);
135
        }
136
137
        /**
138
         * get geo cordinates and address data
139
         * update coordinate and address text fields
140
         */
141
        function updateLocation(latlng) {
142
            if(latlng == null)
143
                latlng = map.getCenter();
144
            geocoder.geocode({'location':latlng},function(r,status){
145
                if (status != google.maps.GeocoderStatus.OK) 
146
                    return;
147
                var z = map.getZoom();
148
                var addr;
149
                var addr_string;
150
                $('#geo_long').val(latlng.lng());
151
                $('#geo_lat').val(latlng.lat());
152
                var Addr = getAddressElements(r[0].address_components);
153
                if (z> 8 && Addr.locality != '')
154
                    $('#address').val(Addr.locality+', '+Addr.country);
155
                else
156
                    $('#address').val(Addr.country_long);
157
            });
158
        }
159
160
        /**
161
         * add new draggeable marker
162
         */
163
164
        function addMarker(latlng,z,bounds) {
165
            if(marker != undefined)
166
                marker.setMap(null);
167
            marker = new google.maps.Marker({position: latlng, map: map,draggable: true});
168
            google.maps.event.addListener(marker,'dragend', function() {
169
                updateLocation(marker.getPosition());
170
            });
171
            if(bounds == null) {
172
                map.setCenter(latlng);
173
                map.setZoom(z);
174
                updateLocation(latlng);
175
            } else {
176
                google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
177
                    updateLocation(null);
178
                });
179
                map.fitBounds(bounds);
180
            }
181
        }
182
183
        /**
184
         * create a marker from the address entered
185
         * by the user
186
         */
187
        function getAddressLocation() {
188
            var city = $('#address').val();
189
            if(city == '') {
190
                alert(\"" . _("nothing entered in the address field") . "\");
191
                return false;
192
            }
193
            geocoder.geocode( { 'address': city}, function(results, status) {
194
                if (status == google.maps.GeocoderStatus.OK) {
195
                    position = results[0].geometry.location;
196
                } else {
197
                    position = center_pl;
198
                    alert('Unable to locate address: ' + status);
199
                    zoom = 6;
200
                }
201
                addMarker(position,zoom,null);
202
                return false;
203
            });
204
        }
205
206
        /**
207
         * trigger geolocation
208
         */
209
        function locateMe() {
210
            $('#address').val(\"" . _("locating") . "\");
211
            navigator.geolocation.getCurrentPosition(locate_succes,locate_fail,{maximumAge:3600000, timeout:5000});
212
        }
213
214
        function locate_succes(p) {
215
            var point = new google.maps.LatLng(p.coords.latitude,p.coords.longitude);
216
            addMarker(point,15,null);
217
        }
218
        function locate_fail(p) {
219
            alert('failure: '+p.message);
220
        }
221
222
223
        /**
224
         * add locations from the markers structure
225
         */
226
        function addLocations() {
227
            if(markers == undefined)
228
                return(0);
229
            google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
230
                z = map.getZoom();
231
                if(mode == 0)
232
                    map.setZoom(z+1);
233
                map.setOptions({maxZoom: 21})
234
            });
235
            xml = parse_xml(markers);
236
            var mrk = xml.documentElement.getElementsByTagName('marker');
237
            var i = 0;
238
            var  area = new google.maps.LatLngBounds();
239
            for (i = 0; i < mrk.length; i++) {
240
                var point = new google.maps.LatLng(parseFloat(mrk[i].getAttribute('lat')),
241
                parseFloat(mrk[i].getAttribute('lng')));
242
                m = new google.maps.Marker({position: point,icon: icon, map: map});
243
                m.info = mrk[i].getAttribute('name');
244
                marks.push(m)
245
                google.maps.event.addListener(m,'click', function() {
246
                    markerClicked(this);
247
                });
248
                area.extend(point);
249
            }
250
            if(mode == 1)
251
                map.setOptions({maxZoom: 18})
252
            else
253
                map.setOptions({maxZoom: 15})
254
            map.fitBounds(area);
255
        }
256
257
        /**
258
         * Google maps innitialize function
259
         * if mode == 1 then enable editing;
260
         */
261
        function load(l) {
262
            mode = l;
263
            if(mode == 0 && markers == undefined)
264
                return;
265
            geocoder = new google.maps.Geocoder();
266
            var myOptions = {
267
                zoom: 3,
268
                center: new google.maps.LatLng(center_lat,center_lng),
269
                streetViewControl: false,
270
                mapTypeControl: false,
271
                zoomControl: false,
272
                mapTypeId: google.maps.MapTypeId.ROADMAP
273
            }
274
275
            icon = new google.maps.MarkerImage('../resources/images/icons/location_marker.png',
276
            new google.maps.Size(40,24),  new google.maps.Point(0,0),  new google.maps.Point(14,0));
277
            icon_red = new google.maps.MarkerImage('../resources/images/icons/location_marker_highlighted.png',
278
            new google.maps.Size(40,24),  new google.maps.Point(0,0),  new google.maps.Point(14,0));
279
            info_window = new google.maps.InfoWindow({disableAutoPan: true,});
280
            map = new google.maps.Map(document.getElementById('map'),myOptions);
281
            if(mode == 1) 
282
                map.setOptions({zoomControl: true});
283
284
            if(addLocations() == 0)
285
                locator_magic();
286
        } " .
287
                '$(document).ready(function () {
288
        $(".location_button").click(function (event) {
289
            event.preventDefault();
290
            marker_index = $(this).attr("id").substr(11) - 1;
291
            marks[marker_index].setOptions({icon: icon_red});
292
            setTimeout("marks[marker_index].setOptions({icon: icon})", 1000);
293
        });
294
295
        $("#address").keypress(function (event) {
296
            if (event.which === 13) {
297
                event.preventDefault();
298
                getAddressLocation();
299
            }
300
301
        });
302
303
    });' .
304
                "</script>";
305
    }
306
307
    public function htmlBodyCode() {
308
        
309
    }
310
311
    public function htmlShowtime($wizard = FALSE, $additional = FALSE) {
312
        if ($this->readOnly) {
313
            return "<div id='map' class='googlemap'></div>";
314
        } else {
315
            return $this->htmlPreEdit($wizard, $additional) . $this->findLocationHtml() . "<div id='map' class='googlemap'></div>" . $this->htmlPostEdit(FALSE);
316
        }
317
    }
318
319
    public static function optionListDisplayCode($coords, $number) {
320
        return "<button id='location_b_" . $number . "' class='location_button'>" . _("Click to see location") . " $number</button>";
321
    }
322
323
    public function bodyTagCode() {
324
        return "onload='load(" . ($this->readOnly ? "0" : "1") . ")'";
325
    }
326
327
    private function findLocationHtml() {
328
        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>";
329
    }
330
331
}
332