summaryrefslogtreecommitdiffstats
path: root/js/geofield_ymap.js
blob: d88e2a181423e273eb2a1c831cbeb30d90284bb5 (plain)
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
(function ($) {
  Drupal.behaviors.geofieldYmap = {
    attach: function (context, settings) {
      $('div.geofield-ymap', context).once('geofield-ymap', function () {
        var mapId = this.id;
        if (!mapId) {
          mapId = this.id = Drupal.geofieldYmap.generateMapId();
        }
        ymaps.ready(function () {
          Drupal.geofieldYmap.mapInit(mapId);
        });
      });
    }
  };

  Drupal.geofieldYmap = Drupal.geofieldYmap || {
    data: {},

    defaultSettings: {
      type: 'yandex#map',
      center: [0, 0],
      zoom: 0,
      auto_centering: false,
      auto_zooming: false,
      controls: ['mediumMapDefaultSet'],
      editable: false,
      multiple: false,
      input_id: '',
      object_types: [],
      object_preset: '',
      objects: '',
      clusterize: false,
    },

    /**
     * Initialize map
     */
    mapInit: function (mapId, settings) {
      var dataSettings = Drupal.geofieldYmap.getDataSettings(mapId);
      settings = $.extend({}, Drupal.geofieldYmap.defaultSettings, dataSettings, settings);

      // Create map
      var map = Drupal.geofieldYmap.createMap(mapId, settings);

      // Set geo objects global options
      var globalOptions = {strokeWidth: 4};
      if (Drupal.settings.geofieldYmap.preset) {
        globalOptions.preset = Drupal.settings.geofieldYmap.preset;
      }
      if (settings.object_preset) {
        globalOptions.preset = settings.object_preset;
      }
      map.geoObjects.options.set(globalOptions);

      // Add geo objects
      if (settings.objects) {
        Drupal.geofieldYmap.addObject(map, settings.objects, settings.editable, settings.clusterize);
      }
      else if (settings.editable && settings.input_id) {
        var objects = $('#' + settings.input_id).val();
        Drupal.geofieldYmap.addObject(map, objects, settings.editable);
      }

      // Auto centering
      if (settings.auto_centering || (settings.center[0] == 0 && settings.center[1] == 0)) {
        Drupal.geofieldYmap.autoCentering(map);
      }

      // Auto zooming
      if ((settings.auto_zooming && map.geoObjects.getLength()) || !settings.zoom) {
        Drupal.geofieldYmap.autoZooming(map);
      }
      else if (settings.auto_zooming) {
        map.setZoom(settings.zoom);
      }

      // Editing features
      if (settings.editable) {
        Drupal.geofieldYmap.addEditButtons(map, settings.object_types);
        map.geoObjects.events.add('remove', Drupal.geofieldYmap.objectsChangeEvent);
        map.events.add('click', Drupal.geofieldYmap.mapClickEvent);
      }

      // Tweak search control
      Drupal.geofieldYmap.tweakSearchControl(map);

      $('#' + mapId).trigger('yandexMapInit', [map]);

      return map;
    },

    /**
     * Create map
     */
    createMap: function (mapId, settings) {
      var map = new ymaps.Map(mapId, {
        type:     settings.type,
        center:   settings.center,
        zoom:     settings.auto_zooming ? 1 : settings.zoom,
        controls: settings.controls
      });
      map.mapId = mapId;

      Drupal.geofieldYmap.data[mapId] = {
        map: map,
        settings: settings,
        editButtons: {},
        cursor: null,
        drawingMode: false
      };

      return map;
    },

    /**
     * Return map data-* settings
     */
    getDataSettings: function (mapId) {
      var settings = {};
      if (mapId && $('#' + mapId).length) {
        var $map = $('#' + mapId);
        $.each(Drupal.geofieldYmap.defaultSettings, function (key, value) {
          var dataAttrName = 'map-' + key.replace('_', '-');
          var dataAttrValue = $map.data(dataAttrName);
          if (dataAttrValue !== undefined && dataAttrValue !== '') {
            settings[key] = ($.type(value) === 'array') ? dataAttrValue.split(',') : dataAttrValue;
          }
        });
      }
      return settings;
    },

    /**
     * Add edit buttons
     */
    addEditButtons: function(map, buttonTypes) {
      if (!buttonTypes) return;

      var buttonTitles = {
        point:   Drupal.t('Add point'),
        line:    Drupal.t('Add line'),
        polygon: Drupal.t('Add polygone'),
      }

      $.each(buttonTypes, function (index, buttonType) {
        var button = new ymaps.control.Button({
          data: {
            image: Drupal.settings.geofieldYmap.modulePath + '/images/icon-' + buttonType + '.png',
            title: buttonTitles[buttonType]
          }
        });
        button.events.add('click', Drupal.geofieldYmap.editButtonClickEvent);
        map.controls.add(button);
        Drupal.geofieldYmap.data[map.mapId].editButtons[buttonType] = button;
      });
      
      return Drupal.geofieldYmap.data[map.mapId].editButtons;
    },

    /**
     * Deselect controls
     */
    deselectControls: function (map) {
      // Deselect edit buttons
      $.each(Drupal.geofieldYmap.data[map.mapId].editButtons, function (buttonName, button) {
        button.deselect();
      });
      
      // Deselect ruler
      var rulerControl = map.controls.get('rulerControl');
      if (rulerControl) {
        rulerControl.deselect();
      }
    },

    /**
     * Add geo object
     */
    addObject: function (map, object, editMode, clusterize) {
      if (!object) return;

      if ($.type(object) === 'string')  {
        object = JSON.parse(object);
      }

      var geoQueryResult = ymaps.geoQuery(object);

      // Clusterize placemarks
      if (clusterize) {
        var points = geoQueryResult.search('geometry.type = "Point"');
        var notPoints = geoQueryResult.search('geometry.type != "Point"');
        map.geoObjects.add(points.clusterize({
          hasBalloon: false,
          hasHint: false,
          margin: 15
        }));
        notPoints.addToMap(map);
      }
      else {
        geoQueryResult.addToMap(map);
      }

      // Enable edit mode
      if (editMode) {
        geoQueryResult.addEvents(['mapchange', 'editorstatechange', 'dragend', 'geometrychange'], Drupal.geofieldYmap.objectsChangeEvent);
        geoQueryResult.addEvents('editorstatechange', Drupal.geofieldYmap.objectEditorStateChangeEvent);
        geoQueryResult.addEvents('dblclick', Drupal.geofieldYmap.objectsDblclickEvent);
        geoQueryResult.setOptions({draggable: true});
        geoQueryResult.each(function (object) {
          object.editor.startEditing();
        });
      }
    },

    /**
     * Add geo object by type
     */
    addObjectByType: function (map, objectType, geometry, editMode, startDrawing) {
      if (objectType == 'point') {
        var object = new ymaps.Placemark(geometry);
      }
      else if (objectType == 'line') {
        var object = new ymaps.Polyline(geometry);
      }
      else if (objectType == 'polygon') {
        var object = new ymaps.Polygon(geometry);
      }
      Drupal.geofieldYmap.addObject(map, object, editMode);

      if (startDrawing) {
        object.editor.startDrawing();
      }
    },

    /**
     * Return map.geoObjects in GeoJSON format
     */
    getObjectsInGeoJson: function (map) {
      var objects = {
        type: 'FeatureCollection',
        features: []
      };
      map.geoObjects.each(function(object) {
        var feature = {
          type: 'Feature',
          geometry: {
            type: object.geometry.getType(),
            coordinates: object.geometry.getCoordinates()
          }
        };
        objects.features.push(feature);
      });
      return JSON.stringify(objects);
    },

    /**
     * Auto centering map
     */
    autoCentering: function(map) {
      if (map.geoObjects.getLength() == 0) return;
      var centerAndZoom = ymaps.util.bounds.getCenterAndZoom(
        Drupal.geofieldYmap.getGeoObjectsBounds(map),
        map.container.getSize()
      );
      map.setCenter(centerAndZoom.center);
    },

    /**
     * Auto zooming map
     */
    autoZooming: function(map) {
      if (map.geoObjects.getLength() == 0) return;
      var mapSize = map.container.getSize();
      var centerAndZoom = ymaps.util.bounds.getCenterAndZoom(
        Drupal.geofieldYmap.getGeoObjectsBounds(map),
        mapSize,
        ymaps.projection.wgs84Mercator,
        {margin: 30}
      );
      map.setZoom(centerAndZoom.zoom <= 16 ? centerAndZoom.zoom : 16);
    },

    /**
     * Return new map id
     */
    generateMapId: function (number) {
      if (!number) number = 1;
      var mapId = 'geofield-ymap-' + number;
      if ($('#' + mapId).length > 0) {
        return Drupal.geofieldYmap.generateMapId(number + 1);
      }
      return mapId;
    },

    /**
     * Return bounds of map.geoObjects
     */
    getGeoObjectsBounds: function (map) {
      var boundsCollection = [map.geoObjects.getBounds()];
      map.geoObjects.each(function (object) {
        if (object.options.getName() == 'clusterer') {
          boundsCollection.push(object.getBounds());
        }
      });
      return Drupal.geofieldYmap.getTotalBounds(boundsCollection);
    },

    /**
     * Return total bounds by bounds collection
     */
    getTotalBounds: function (boundsCollection) {
      var totalBounds;

      $.each(boundsCollection, function (index, bounds) {
        if (!bounds) {
          return;
        }
        if (!totalBounds) {
          totalBounds = bounds;
          return;
        }

        // Min
        if (totalBounds[0][0] > bounds[0][0]) totalBounds[0][0] = bounds[0][0];
        if (totalBounds[0][1] > bounds[0][1]) totalBounds[0][1] = bounds[0][1];
        // Max
        if (totalBounds[1][0] < bounds[1][0]) totalBounds[1][0] = bounds[1][0];
        if (totalBounds[1][1] < bounds[1][1]) totalBounds[1][1] = bounds[1][1];
      });

      return totalBounds;
    },

    /**
     * Tweak search control
     */
    tweakSearchControl: function (map) {
      var searchControl = map.controls.get('searchControl');
      if (searchControl) {
        // Remove search result placemark after close balloon
        searchControl.events.add('resultshow', function (event) {
          var resultIndex = event.get('index');
          var result = searchControl.getResultsArray()[resultIndex];
          result.balloon.events.add('close', function (event) {
            result.getParent().remove(result);
          });
        });

        // Prevent submit parent form in map search control
        $('#' + map.mapId).delegate('.ymaps-search .ymaps-input__control', 'keypress', function (event) {
          if (event.keyCode == 13) {
            event.preventDefault();
          }
        });
      }
    },

    /**
     * Change map cursor
     */
    changeCursor: function (map, cursor) {
      var cursorAccessor = Drupal.geofieldYmap.data[map.mapId].cursor;
      if (!cursorAccessor || !cursorAccessor.getKey(cursor)) {
        cursorAccessor = map.cursors.push(cursor);
      }
      else {
        cursorAccessor.setKey(cursor);
      }
    },

    /**
     * Return selected edit button
     */
    getSelectedEditButton: function (map) {
      var settings = Drupal.geofieldYmap.data[map.mapId].settings;
      var editButtons = Drupal.geofieldYmap.data[map.mapId].editButtons;

      for (buttonName in editButtons) {
        var button = editButtons[buttonName];
        if (button.state.get('selected')) {
          return button;
        }
      }
    },

    /**
     * Edit button click handler
     */
    editButtonClickEvent: function (event) {
      var button = event.get('target');
      var map = button.getMap();

      if (!button.state.get('selected')) {
        Drupal.geofieldYmap.deselectControls(map);
        Drupal.geofieldYmap.changeCursor(map, 'arrow');
      }
      else {
        Drupal.geofieldYmap.changeCursor(map, 'grab');
      }
    },

    /**
     * Object editorstatechange event
     */
    objectEditorStateChangeEvent: function (event) {
      var object = event.get('target');
      var map = object.getMap();
      if (map) {
        Drupal.geofieldYmap.data[map.mapId].drawingMode = object.editor.state.get('drawing');
      }
    },

    /**
     * Objects change handler
     */
    objectsChangeEvent: function (event) {
      var object = event.get('target');
      var map = object.getMap();
      if (map) {
        var $map = $('#' + map.mapId);
        var $input = $('#' + $map.data('map-input-id'));
        $input.val(Drupal.geofieldYmap.getObjectsInGeoJson(map));
      }
    },

    /**
     * Object dblclick handler
     */
    objectsDblclickEvent: function (event) {
      var object = event.get('target');
      var map = object.getMap();
      map.geoObjects.remove(object);
      event.stopPropagation();
    },

    /**
     * Map click handler
     */
    mapClickEvent: function (event) {
      var map = event.get('target');
      var settings = Drupal.geofieldYmap.data[map.mapId].settings;
      var selectedButton = Drupal.geofieldYmap.getSelectedEditButton(map);

      if (selectedButton && !Drupal.geofieldYmap.data[map.mapId].drawingMode) {
        if (!settings.multiple) {
          map.geoObjects.removeAll();
        }

        var geometry = event.get('coords');
        var startDrawing = false;
        if (buttonName == 'line') {
          geometry = [geometry];
          startDrawing = true;
        }
        else if (buttonName == 'polygon') {
          geometry = [[geometry]];
          startDrawing = true;
        }
        Drupal.geofieldYmap.addObjectByType(map, buttonName, geometry, true, startDrawing);
      }
    },
  };
})(jQuery);