-
Notifications
You must be signed in to change notification settings - Fork 0
/
WME-Get-Address-POI.user.js
1350 lines (1204 loc) · 71 KB
/
WME-Get-Address-POI.user.js
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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ==UserScript==
// @name WME getting info from 2GIS
// @namespace https://greasyfork.org/ru/scripts/19633-wme-getting-info-from-2gis
// @version 0.1.7.18
// @description Information from 2gis in landmark edit panel
// @author coilamo & skirda
// @include https://*.waze.com/editor/*
// @include https://*.waze.com/*/editor/*
// @include https://*.waze.com/map-editor/*
// @include https://*.waze.com/beta_editor/*
// @grant none
// Спасибо skirda за помощь в улучшении скрипта
// ==/UserScript==
var WME_2gis_version = '0.1.7.18';
var wazeActionAddLandmark = require("Waze/Action/AddLandmark");
var wazefeatureVectorLandmark = require("Waze/Feature/Vector/Landmark");
var wazefeatureEditorLandmark = require("Waze/Modules/FeatureEditor/Landmark");
var wazeActionUpdateFeatureAddress = require("Waze/Action/UpdateFeatureAddress");
var wazeActionUpdateObject = require("Waze/Action/UpdateObject");
var wme2GIS_debug=false;
var wme2GIS_dontselect=false;
var wme2GIS_changecat = false;
var wme2GIS_AddAddress=false;
var wme2GIS_UserRank=-1;
var wme2GIS_radius=10;
var wme2GIS_NavigationPoint=0; // размещать точки-пои рандомно, недалеко от точки входа
var wme2GIS_HNFormat=0;
var wme2GIS_DefCategory="OTHER";
var wme2GIS_osmmap=false;
var wme2GIS_yamap=false;
var wme2GIS_2gismap=false;
var wme2GIS_gmmap=false; // TODO!!!
//Waze.selectionManager.selectedItems[0].model.getNavigationPoint().point
function cloneConfig(obj)
{
if (null == obj || "object" != typeof obj) return obj;
var copy = obj.constructor();
for (var attr in obj)
{
if (obj.hasOwnProperty(attr))
{
copy[attr] = cloneConfig(obj[attr]);
}
}
return copy;
}
function CreateID()
{
return 'WME-2Gis-' + WME_2gis_version.replace(/\./g,"-");
}
function PtInPoly(x, y, components)
{
npol = components.length;
jj = npol - 1;
var c = 0;
for (var ii = 0; ii < npol;ii++)
{
if ((((components[ii].y<=y) && (y<components[jj].y)) || ((components[jj].y<=y) && (y<components[ii].y))) &&
(x > (components[jj].x - components[ii].x) * (y - components[ii].y) / (components[jj].y - components[ii].y) + components[ii].x))
{
c = !c;
}
jj = ii;
}
return c;
}
function IsJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
function wme_2gis() {
console.log('Starting wme_2gis');
if (typeof Waze === "undefined")
{
console.log("undef Waze");
setTimeout(wme_2gis,500);
return;
}
if (typeof Waze.selectionManager === "undefined")
{
console.log("undef Waze.selectionManager");
setTimeout(wme_2gis,500);
return;
}
if (typeof Waze.model === "undefined")
{
console.log("undef Waze.model");
setTimeout(wme_2gis,500);
return;
}
if (typeof Waze.loginManager === "undefined")
{
console.log("undef Waze.loginManager");
setTimeout(wme_2gis,500);
return;
}
if (typeof Waze.loginManager.user === "undefined" || Waze.loginManager.user === null)
{
console.log("Waze.loginManager.user undefined OR null");
setTimeout(wme_2gis,500);
return;
}
try {
Waze.selectionManager.events.register("selectionchanged", null, wme_2gis_InserHTML);
}
catch (err) {
console.log('wme_2gis error: '+err.message);
}
wme2GIS_AddAddress = __GetLocalStorageItem("wme2GIS_AddAddress",'bool',false);
wme2GIS_dontselect = __GetLocalStorageItem("wme2GIS_dontselect",'bool',false);
wme2GIS_changecat = __GetLocalStorageItem("wme2GIS_changecat",'bool',false);
wme2GIS_NavigationPoint = __GetLocalStorageItem("wme2GIS_NavigationPoint",'int',0);
wme2GIS_HNFormat = __GetLocalStorageItem("wme2GIS_HNFormat",'int',0);
wme2GIS_radius = __GetLocalStorageItem("wme2GIS_radius",'int',10);
try {
wme2GIS_UserRank = __GetLocalStorageItem("wme2GIS_UserRank",'int',Waze.loginManager.user.rank);
}
catch (err) {
console.log('wme_2gis error: '+err.message);
}
try {
wme2GIS_DefCategory = __GetLocalStorageItem("wme2GIS_DefCategory",'arr','PROFESSIONAL_AND_PUBLIC',I18n.translations[I18n.locale].venues.categories);
}
catch (err) {
console.log('wme_2gis error: '+err.message);
}
setTimeout(wme_2gis_initBindPoi, 500);
setTimeout(Wme2Gis_InitConfig, 500);
}
function wme_2gis_InserHTML() {
if (wme2GIS_debug) console.log("wme_2gis_InserHTML()");
if (Waze.selectionManager.selectedItems.length > 0 && Waze.selectionManager.selectedItems[0].model.type === "venue") {
if (wme2GIS_debug) console.log('wme_2gis_InserHTML');
$('#landmark-edit-general').prepend(
'<div class="form-group"> \
<label class="control-label">External POI (version ' + WME_2gis_version + ')</label> \
<div class="controls"> \
<div id="2gis0"><div id="2gis"></div><div id="map_2gis"></div></div> \
<div id="gm0"><div id="gm"></div><div id="street-view"></div></div> \
<div id="ym0"><div id="ym"></div><div id="map_ya"></div></div> \
<div id="osm0"><div id="osm"></div><div id="map_osm"></div></div> \
</div> \
</div> \
</div>'
);
var div2gis = document.getElementById('2gis');
var divGm = document.getElementById('gm');
var divYm = document.getElementById('ym');
var divOsm = document.getElementById('osm');
document.getElementById("map_2gis").setAttribute('style',wme2GIS_2gismap?'width:275px; height:275px':'display:none;');
document.getElementById("map_ya").setAttribute('style',wme2GIS_yamap?'width:275px; height:275px':'display:none;');
document.getElementById("map_osm").setAttribute('style',wme2GIS_osmmap?'width:275px; height:275px':'display:none;');
document.getElementById("street-view").setAttribute('style',wme2GIS_gmmap?'width:275px; height:275px':'display:none;');
//getting lon/lat selected point
var poi_id=Waze.selectionManager.selectedItems[0].model.attributes.id;
//if (wme2GIS_debug) console.log(Waze.model.venues.get(poi_id).geometry);
// координаты всегда берём от мыши
var mc=document.getElementsByClassName('WazeControlMousePosition')[0].lastChild.innerHTML.split(' ');
var x=mc[0];
var y=mc[1];
var poiPos=new OpenLayers.LonLat(x,y);
if (wme2GIS_debug) console.log("https://www.waze.com/ru/editor/?env=row&lon="+poiPos.lon+"&lat="+poiPos.lat+"&zoom=7&marker=yes");
//2GIS
var url = 'https://catalog.api.2gis.ru/2.0/geo/search';
var data = {
"point": poiPos.lon + ',' + poiPos.lat,
"format": "json",
"fields": "items.links",
"key": "rubnkm7490"
};
$.ajax({
dataType: "json",
cache: false,
url: url,
data: data,
error: function() {
},
success: function(json) {
if(!json.result)
{
document.getElementById("map_2gis").setAttribute('style','display:none;');
return;
}
if(wme2GIS_2gismap){
var script2 = document.createElement('script');
script2.type = "text/javascript";
var s = document.getElementsByTagName('head')[0].appendChild(script2);
s.innerHTML='var map; DG.then(function () {map = DG.map(\'map_2gis\', {center: [' + poiPos.lat + ',' + poiPos.lon + '],zoom: 17,fullscreenControl: false,zoomControl: false});});';
}
div2gis.innerHTML = '2GIS: ' + json.result.items[0].full_name + '<br/>';
// у точки не отображаем организайии, если она в пределах родителя
var ispoint=Waze.selectionManager.hasSelectedItems() && Waze.selectionManager.selectedItems[0].model.attributes.geometry.id.indexOf(".Point") >= 0;
var found=false;
if(ispoint)
{
for(var i in Waze.model.venues.objects) // ищем родителя
{
var v=Waze.model.venues.get(i);
if (v.attributes.geometry.id.indexOf(".Point") < 0) // исключаем точки
{
var poiCoord=new OpenLayers.LonLat(poiPos.lon,poiPos.lat);
poiCoord.transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));
if (PtInPoly(poiCoord.lon,poiCoord.lat,v.attributes.geometry.components[0].components))
{
found=true;
break;
}
}
if(found)
break;
}
}
if (wme2GIS_debug) console.log("wme_2gis_InserHTML(): found parent="+found);
if (!found)
{
if(json.result.items.length > 0)
{
if(json.result.items[0].links && typeof (json.result.items[0].links) === "object")
{
if(typeof (json.result.items[0].links.branches) !== "undefined")
{
div2gis.innerHTML += '<div id="poi_2gis" style="width:275px;"><a href="#" id="getListPoi">Организации в здании</a></div>';
document.getElementById('getListPoi').onclick = getListPOI;
document.getElementById('getListPoi').setAttribute('building_id', json.result.items[0].id);
document.getElementById('getListPoi').setAttribute('lat', poiPos.lat);
document.getElementById('getListPoi').setAttribute('lon', poiPos.lon);
document.getElementById('getListPoi').setAttribute('page', 1);
}
}
}
}
}
});
//google maps
var gm_url = 'https://maps.googleapis.com/maps/api/geocode/json';
var gm_data = {
"latlng": poiPos.lat + ',' + poiPos.lon
};
$.ajax({
dataType: "json",
cache: false,
url: gm_url,
data: gm_data,
error: function() {
},
success: function(json) {
if(!json.results)
{
document.getElementById("street-view").setAttribute('style','display:none;');
return;
}
var gm_obj = json.results[0].address_components;
//window.gm_obj=gm_obj;
if(gm_obj[0].long_name !== 'Unnamed Road') {
divGm.innerHTML='GM: <a href="#" id="gm_storeaddress" title="Заполнить адрес">'+gm_obj[0].long_name + ', ' + gm_obj[1].long_name+'</a>';
//var StreetViewPanorama=
new google.maps.StreetViewPanorama(
document.getElementById('street-view'),
{
position: {lat: poiPos.lat, lng: poiPos.lon},
pov: {heading: 165, pitch: 0},
zoom: 1
});
// StreetViewPanorama.setPov({ heading: 90, pitch: 0, zoom: 1 })
document.getElementById('gm_storeaddress').onclick = __ModityAddressYM;
if(gm_obj[2].long_name !== null)
document.getElementById('gm_storeaddress').setAttribute('cityName', gm_obj[2].long_name);
if(gm_obj[1].long_name !== null)
document.getElementById('gm_storeaddress').setAttribute('streetName', gm_obj[1].long_name);
if(gm_obj[0].long_name !== null)
document.getElementById('gm_storeaddress').setAttribute('houseNumber', gm_obj[0].long_name);
}
else
{
document.getElementById("street-view").setAttribute('style','display:none;');
divGm.innerHTML='GM: ЗДЕСЬ РЫБЫ НЕТ!'; //!!!!!
}
}
});
//yandex maps
var ym_url = 'https://geocode-maps.yandex.ru/1.x/';
var ym_data = {
"geocode": poiPos.lon + ',' + poiPos.lat,
"format":"json"
};
$.ajax({
dataType: "json",
cache: false,
url: ym_url,
data: ym_data,
error: function() {
},
success: function(json) {
if(!json.response)
{
document.getElementById("map_ya").setAttribute('style','display:none;');
return;
}
function findSomething(object, name) {
//if (wme2GIS_debug) console.log(object);
if (name in object) return object[name];
for (key in object) {
if ((typeof (object[key])) == 'object') {
var t = findSomething(object[key], name);
if (t) return t;
}
}
return null;
}
var ym_obj = json.response.GeoObjectCollection.featureMember[0].GeoObject;
var cityName = findSomething(ym_obj, "LocalityName");
var streetName;
if(findSomething(ym_obj, "ThoroughfareName") !== null) {
streetName = findSomething(ym_obj, "ThoroughfareName");
} else if(findSomething(ym_obj, "DependentLocalityName") !== null) {
streetName = findSomething(ym_obj, "DependentLocalityName");
}
var houseNumber = findSomething(ym_obj, "PremiseNumber");
var innerHTML=((houseNumber !== undefined && houseNumber !== null) || wme2GIS_yamap)?'YM: ':'';
if(houseNumber !== undefined && houseNumber !== null)
innerHTML+='<a href="#" id="ym_storeaddress" title="Заполнить адрес">' + houseNumber + ', ' + streetName + '</a>';
divYm.innerHTML=innerHTML;
if(houseNumber !== undefined && houseNumber !== null)
{
if (document.getElementById('ym_storeaddress')) document.getElementById('ym_storeaddress').onclick = __ModityAddressYM;
var ym_locality = findSomething(ym_obj, "LocalityName");
if(typeof(ym_locality.DependentLocality) !== undefined) ym_locality = ym_locality.DependentLocality;
if(cityName !== null && document.getElementById('ym_storeaddress'))
document.getElementById('ym_storeaddress').setAttribute('cityName', cityName);
if(streetName !== null && document.getElementById('ym_storeaddress'))
document.getElementById('ym_storeaddress').setAttribute('streetName', streetName);
if(houseNumber !== null && document.getElementById('ym_storeaddress'))
document.getElementById('ym_storeaddress').setAttribute('houseNumber', houseNumber);
}
if(wme2GIS_yamap){
var map = new ymaps.Map("map_ya", {
center: [poiPos.lat, poiPos.lon],
zoom: 17,
controls: ["zoomControl", "fullscreenControl"]
});
}
}
});
//OSM
var osm_url = 'https://nominatim.openstreetmap.org/reverse';
var osm_data = {
"lat": poiPos.lat,
"lon": poiPos.lon,
"zoom": 20,
"format": "json",
"addressdetails": 1,
"countrycodes":"ru",
"accept-language": "Ru_ru"
};
$.ajax({
dataType: "json",
cache: false,
url: osm_url,
data: osm_data,
error: function() {
},
success: function(json) {
if(!json.address)
{
document.getElementById("map_osm").setAttribute('style','display:none;');
return;
}
var osm_obj = json.address;
if(!(osm_obj.house_number !== undefined || wme2GIS_osmmap))
{
document.getElementById("map_osm").setAttribute('style','display:none;');
return; // лишнее не отображаем
}
var innerHTML=osm_obj.house_number !== undefined || wme2GIS_osmmap?'OSM: ':'';
//window.osm_obj=osm_obj;
if(osm_obj.house_number !== undefined)
innerHTML+='<a href="#" id="osm_storeaddress" title="Заполнить адрес">'+osm_obj.house_number + ', ' + osm_obj.road + '</a>';
divOsm.innerHTML=innerHTML;
if(osm_obj.house_number !== undefined)
{
if (document.getElementById('osm_storeaddress'))
{
document.getElementById('osm_storeaddress').onclick = __ModityAddressYM;
document.getElementById('osm_storeaddress').setAttribute('cityName', osm_obj.city);
document.getElementById('osm_storeaddress').setAttribute('streetName', osm_obj.road);
document.getElementById('osm_storeaddress').setAttribute('houseNumber', osm_obj.house_number);
}
}
if(wme2GIS_osmmap)
{
//Google maps API initialisation
var element = document.getElementById("map_osm");
var map = new google.maps.Map(element, {
center: new google.maps.LatLng(poiPos.lat, poiPos.lon),
zoom: 17,
mapTypeId: "OSM",
mapTypeControl: false,
streetViewControl: false
});
//Define OSM map type pointing at the OpenStreetMap tile server
map.mapTypes.set("OSM", new google.maps.ImageMapType({
getTileUrl: function(coord, zoom) {
return "http://tile.openstreetmap.org/" + zoom + "/" + coord.x + "/" + coord.y + ".png";
},
tileSize: new google.maps.Size(256, 256),
name: "OpenStreetMap",
maxZoom: 18
}));
}
}
});
}
return;
}
function __ModityAddressYM()
{
var cityName=this.getAttribute('cityname');
if (wme2GIS_debug) console.log(cityName);
var streetName=this.getAttribute('streetname');
if (wme2GIS_debug) console.log(streetName);
var houseNumber=this.getAttribute('housenumber');
if (wme2GIS_debug) console.log(houseNumber);
var mod=false;
function GetControlName(id)
{
var beta = (location.hostname == "editor-beta.waze.com"?true:false);
switch(id)
{
case 'form':
return beta?".edit-button":".edit-button";
case 'cityname':
return beta?'class="city-name form-control"':'class="city-name form-control"';
case 'citynamecheck':
return beta?".empty-city":".empty-city";
case 'streetname':
return beta?'class="form-control street-name"':'class="form-control street-name"';
case 'streetnamecheck':
return beta?".empty-street":".empty-street";
case 'housenumber':
return beta?'class="form-control house-number"':'class="form-control house-number"';
case 'save':
return beta?'class="btn btn-primary save-button"':'class="btn btn-primary save-button"';
case 'cancel':
return beta?'class="btn btn-default cancel-button"':'class="btn btn-default cancel-button"';
case 'name':
return "name";
}
return '';
}
// кликаем кнопку изменение адреса
$(GetControlName('form')).click();
// открылась форма
setTimeout(function() {
var res=null;
// ** обработка имени стрита **
if(streetName && streetName !== "")
{
//блок по преобразованию имени стрита к нашему виду.
var wmeStreetName;
var streets=[];
var i=0;
for(i in Waze.model.streets.objects)
{
if (wme2GIS_debug) console.log("Waze.model.streets.objects["+i+"].getAttributes().name="+Waze.model.streets.objects[i].getAttributes().name);
if (Waze.model.streets.objects[i].getAttributes().name)
streets.push({"name": Waze.model.streets.objects[i].getAttributes().name});
}
if (wme2GIS_debug) {console.log("streets:");console.log(streets);}
var options = {
caseSensitive: false,
includeScore: false,
shouldSort: true,
tokenize: true,
threshold: 0.6,
location: 0,
distance: 100,
maxPatternLength: 32,
keys: ["name"]
};
var f = new Fuse(streets, options);
wmeStreetName = f.search(streetName);
if (wme2GIS_debug) console.log(wmeStreetName[0].name);
if($('input['+GetControlName('streetname')+']').val() !== wmeStreetName[0].name) {
// если чекед ("без улицы") - сделать uncheck (разлочить строку ввода)
if ($(GetControlName('streetnamecheck'))[0].checked)
$(GetControlName('streetnamecheck')).click();
//если имя не пустое, сообщаем, что мы его меняем
if($('input['+GetControlName('streetname')+']').val().length) {
if(confirm('Изменить улицу ' + $('input['+GetControlName('streetname')+']').val() + ' -> ' + wmeStreetName[0].name + '?'))
{
// ставим имя стрита в адрес
$('input['+GetControlName('streetname')+']').val(wmeStreetName[0].name).change();
mod=true;
}
}else{
// ставим имя стрита в адрес
$('input['+GetControlName('streetname')+']').val(wmeStreetName[0].name).change();
mod=true;
}
}
}
// ** обработка номера дома **
if(houseNumber && houseNumber !== "")
{
// удаляем пробелы
houseNumber=houseNumber.replace(/\s+/g, '');
// сокращаем
houseNumber=houseNumber.replace(/корпус/g, 'к');
houseNumber=houseNumber.replace(/строение/g, 'с');
houseNumber=houseNumber.replace(/владение/g, 'вл');
switch(wme2GIS_HNFormat){
case 0:
// коррекция в соответствии с 2gis
houseNumber=houseNumber.toLowerCase();
if (houseNumber.indexOf("б") > -1) // "Б" делаем большим
houseNumber=houseNumber.toUpperCase();
break;
case 1:
// коррекция в соответствии с yandex
houseNumber=houseNumber.toUpperCase();
if (houseNumber.indexOf("К") > -1) houseNumber=houseNumber.substring(0,houseNumber.lastIndexOf("К")) + houseNumber.substring(houseNumber.lastIndexOf("К"), houseNumber.lastIndexOf("К")+1).toLowerCase() + houseNumber.slice(houseNumber.lastIndexOf("К")+1);
if (houseNumber.indexOf("С") > -1) houseNumber=houseNumber.substring(0,houseNumber.lastIndexOf("С")) + houseNumber.substring(houseNumber.lastIndexOf("С"), houseNumber.lastIndexOf("С")+1).toLowerCase() + houseNumber.slice(houseNumber.lastIndexOf("С")+1);
if (houseNumber.indexOf("ВЛ") > -1) houseNumber=houseNumber.substring(0,houseNumber.lastIndexOf("ВЛ")) + houseNumber.substring(houseNumber.lastIndexOf("ВЛ"), houseNumber.lastIndexOf("ВЛ")+2).toLowerCase() + houseNumber.slice(houseNumber.lastIndexOf("ВЛ")+2);
if (houseNumber.indexOf("ДВ") > -1) houseNumber=houseNumber.substring(0,houseNumber.lastIndexOf("ДВ")) + houseNumber.substring(houseNumber.lastIndexOf("ДВ"), houseNumber.lastIndexOf("ДВ")+2).toLowerCase() + houseNumber.slice(houseNumber.lastIndexOf("ДВ")+2);
break;
case 2:
// коррекция в соответствии с BY
houseNumber=houseNumber.toUpperCase();
houseNumber=houseNumber.replace('К', '/');
break;
default:
break;
}
// валидация
// выносим номер дома в название (если пусто)
if($('input[name="name"]').length > 1)
{
for(var ii=0; ii < $('input[name="name"]').length; ++ii)
{
if (typeof ($($('input[name="name"]')[ii]).attr("id")) === "undefined" && !$($('input[name="name"]')[ii]).val())
{
$($('input[name="name"]')[ii]).val(houseNumber).change();
break;
}
}
}
else
{
if(!$('input[name="name"]').val())
$('input[name="name"]').val(houseNumber).change();
else if($('input[name="name"]').val() !== houseNumber) {
if(confirm ("Изменить Название POI "+$('input[name="name"]').val()+"->"+houseNumber+"?")) {
$('input[name="name"]').val(houseNumber).change();
}
}
}
//ставим лок
if (wme2GIS_debug) console.log("__ModityAddressYM(): userRank="+wme2GIS_UserRank);
if($('select[name="lockRank"]').val() !== wme2GIS_UserRank)
$('select[name="lockRank"]').val(wme2GIS_UserRank).change();
// если ХН пусто или не совпадает с новым
if(!$('input['+GetControlName('housenumber')+']').val() || $('input['+GetControlName('housenumber')+']').val() !== houseNumber)
{
// ... допустимо только " 'цифр в количестве от 1 до 6' И_ВОЗМОЖНО ('буквы' ИЛИ '/буквы' ИЛИ '/цифры') "
if(/^\d{1,6}(([а-яА-Я]*)|(\/{1}(([а-яА-Я]+)|([0-9]+))))$/.test(houseNumber))
{
// можно ставить ХН
$('input['+GetControlName('housenumber')+']').val(houseNumber).change();
mod=true;
}
}
}
// ** обработка имени НП **
if (wme2GIS_debug) console.log("cityName="+cityName)
if(cityName && cityName !== "")
{
if (wme2GIS_debug) console.log("start CITYS");
//блок по преобразованию имени сити к нашему виду.
var wmeCityName;
var citys=[];
var i=0;
for(i in Waze.model.cities.objects)
{
var name_c=Waze.model.cities.objects[i].getAttributes().name;
if (wme2GIS_debug) console.log("Waze.model.cities.objects["+i+"].getAttributes().name="+name_c);
//if (name_c)
citys.push({"name": name_c});
}
if (wme2GIS_debug) { console.log("citys:"); console.log(citys); }
var options = {
caseSensitive: false,
includeScore: false,
shouldSort: true,
tokenize: true,
threshold: 0.6,
location: 0,
distance: 100,
maxPatternLength: 32,
keys: ["name"]
};
var f = new Fuse(citys, options);
wmeCityName = f.search(cityName);
if (wme2GIS_debug) console.log("wmeCityName[0].name="+wmeCityName[0].name);
if($('input['+GetControlName('cityname')+']').val() !== wmeCityName[0].name) {
// если чекед ("без НП") - сделать uncheck (разлочить строку ввода)
if ($(GetControlName('citynamecheck'))[0].checked)
$(GetControlName('citynamecheck')).click();
//если имя не пустое, сообщаем, что мы его меняем
if($('input['+GetControlName('cityname')+']').val().length) {
if(confirm('Изменить НП ' + $('input['+GetControlName('cityname')+']').val() + ' -> ' + wmeCityName[0].name + '?'))
{
// ставим имя стрита в адрес
$('input['+GetControlName('cityname')+']').val(wmeCityName[0].name).change();
mod=true;
}
}else{
// ставим имя стрита в адрес
$('input['+GetControlName('cityname')+']').val(wmeCityName[0].name).change();
mod=true;
}
}
}
if (wme2GIS_debug) console.log("GetControlName('save')="+GetControlName('save'));
$('button['+(mod ?GetControlName('save'):GetControlName('cancel'))+']').click();
}, 60);
// Меняем категорию на по умолчанию
//console.log("$('.category').attr('data-category')="+ $('.category').attr('data-category') +", wme2GIS_DefCategory="+ wme2GIS_DefCategory +", wme2GIS_changecat="+ wme2GIS_changecat)
if($('.category').attr('data-category') !== "OTHER"/*wme2GIS_DefCategory*/ && wme2GIS_changecat) {
if(confirm('Изменить тип пои с ' + $('.category').attr('data-category') + ' на ' + "OTHER"/*wme2GIS_DefCategory*/)) {
$('.remove-choice').each(function(o){this.click();}); //сначала удаляем что есть
$('div[data-category='+"OTHER"/*wme2GIS_DefCategory*/+']').click();
}
}
}
function getListPOI(){
if (wme2GIS_debug) console.log("getListPOI()");
var building_id=this.getAttribute('building_id');
var lonc=this.getAttribute('lon');
var latc=this.getAttribute('lat');
var page=this.getAttribute('page');
var url = 'https://catalog.api.2gis.ru/2.0/catalog/branch/list';
var data = {
"building_id": building_id,
"fields": "items.point",
"page_size": 50,
"page": page,
"key": "rubnkm7490"
};
$.ajax({
dataType: "json",
cache: false,
url: url,
data: data,
error: function() {
},
success: function(json) {
if (wme2GIS_debug) console.dir(json)
if(json.meta.error === undefined) {
var total = parseInt(json.result.total);
var poi_list='';
for (var i = 0; i < total; i++) {
if(json.result.items[i] === undefined) break;
if(__GetLocalStorageItem("wme2GIS_id_" + json.result.items[i].id.split("_")[0],'bool',false)) poi_list+='<a href="#" style="padding-right:5px;" class="fa fa-check-square" poi="' + json.result.items[i].id.split("_")[0] + '"></a>';
else poi_list+='<a href="#" style="padding-right:5px;display:none;" class="fa fa-check-square" poi="' + json.result.items[i].id.split("_")[0] + '"></a>';
poi_list = poi_list + (i+1+(page-1)*50) + '.'
+' <a href="#"'
+' class="create-poi"'
+' lon="' + json.result.items[i].point.lon + '"'
+' lat="' + json.result.items[i].point.lat + '"'
+' poi_id="' + json.result.items[i].id + '"'
+' lonc="' + lonc + '"'
+' latc="' + latc + '"'
+'>' + json.result.items[i].name + '</a><br/>';
}
if(total > 50 && Math.floor(total/50) >= page)
poi_list+='<a href="#" id="nextListPoi">Следующие</a><hr/>';
else
poi_list+='<hr/>';
$("#poi_2gis").html(poi_list);
if(total > 50 && Math.floor(total/50) >= page) {
document.getElementById('nextListPoi').onclick = getListPOI;
document.getElementById('nextListPoi').setAttribute('building_id', building_id);
document.getElementById('nextListPoi').setAttribute('lat', latc);
document.getElementById('nextListPoi').setAttribute('lon', lonc);
document.getElementById('nextListPoi').setAttribute('page', parseInt(page)+1);
}
$('.fa-check-square').click(function(){
localStorage.setItem('wme2GIS_id_' + this.getAttribute('poi'), 0);
console.log('wme2GIS_id_' + this.getAttribute('poi'));
this.remove();
});
}else{
$("#poi_2gis").html(json.meta.error.message);
}
$('.create-poi').click(function(){
//if (wme2GIS_debug) console.log(this.getAttribute('name') + '/' + this.getAttribute('lon') + '/' + this.getAttribute('lat'));
var poiCoord=new OpenLayers.LonLat(this.getAttribute('lon'),this.getAttribute('lat'));
poiCoord.transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));
if (wme2GIS_debug) console.log('[' + poiCoord.lon + '/' + poiCoord.lat + '], [' + this.getAttribute('latc') + '/' + this.getAttribute('lonc') + ']');
createPOI({
x: poiCoord.lon,
y: poiCoord.lat,
poi_id: this.getAttribute('poi_id'),
lat: this.getAttribute('latc'),
lon: this.getAttribute('lonc')
});
});
}
});
}
function createPOI (poiobject) {
if (wme2GIS_debug) console.log("createPOI("+JSON.stringify(poiobject)+")");
/*
poiobject:
x, y - координаты (2гис)
lat,lon - координаты клика мыши (WME)
poi_id - это уникальный идентификатор создаваемого ПОИ (2гис)
*/
var url = 'https://catalog.api.2gis.ru/2.0/catalog/branch/get';
var data = {
"id": poiobject.poi_id,
"format": "json",
"fields": "items.adm_div,items.region_id,items.reviews,items.point,items.links,items.name_ex,items.org,items.group,items.see_also,items.dates,items.external_content,items.flags,items.ads.options,items.email_for_sending.allowed,hash,search_attributes",
"key": "rubnkm7490"
};
$.ajax({
dataType: "json",
cache: false,
url: url,
data: data,
error: function() {
},
success: function(json) {
var json_poi = json.result.items[0];
var poi = new wazefeatureVectorLandmark();
var geometry = new OpenLayers.Geometry.Point();
var rnd_meter=wme2GIS_radius;
switch(wme2GIS_NavigationPoint)
{
case 0: // около точки входа (rnd_meter - в пределах скольки метров)
geometry.x=Waze.selectionManager.selectedItems[0].model.getNavigationPoint().point.x+((Math.random()*10) & 1 ?+1:-1)*(Math.random()*rnd_meter);
geometry.y=Waze.selectionManager.selectedItems[0].model.getNavigationPoint().point.y+((Math.random()*10) & 1 ?+1:-1)*(Math.random()*rnd_meter);
break;
case 1: // там, где кликнули мышкой
var poiPos=new OpenLayers.LonLat(poiobject.lon,poiobject.lat);
// здесь требуется преобразование координат
poiPos.transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));
geometry.x = poiPos.lon;
geometry.y = poiPos.lat;
break;
case 2: // рандомно, в пределах родиетльского ПОИ
while(1)
{
geometry.x = poiobject.x+((Math.random()*10) & 1 ?+1:-1)*(Math.random()*100);
geometry.y = poiobject.y+((Math.random()*10) & 1 ?+1:-1)*(Math.random()*100);
if (PtInPoly(geometry.x,geometry.y,Waze.selectionManager.selectedItems[0].model.attributes.geometry.components[0].components))
break;
}
break;
case 3: // около точки входа 2GIS
var entrance_2gis = [];
if (typeof json_poi.links.entrances !== "undefined")
entrance_2gis = json_poi.links.entrances[0].geometry.points[0].replace(/.*\(([0-9\.]+) ([0-9\.]+)\)/,"$1 $2").split(" ");
else
{
entrance_2gis.push(json_poi.point.lon);
entrance_2gis.push(json_poi.point.lat);
}
var entrancePos=new OpenLayers.LonLat(entrance_2gis[0], entrance_2gis[1]);
// здесь требуется преобразование координат
entrancePos.transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));
geometry.x=entrancePos.lon+((Math.random()*10) & 1 ?+1:-1)*(Math.random()*rnd_meter);
geometry.y=entrancePos.lat+((Math.random()*10) & 1 ?+1:-1)*(Math.random()*rnd_meter);
break;
}
if (wme2GIS_debug) console.log("geometry="+JSON.stringify(geometry));
poi.geometry = geometry;
poi.attributes.categories=Waze.selectionManager.selectedItems[0].model.attributes.categories.clone();
poi.attributes.categories.length=0;
if(json_poi.rubrics !== undefined && typeof wme2Gis_categories[json_poi.rubrics[0].alias] !== "undefined") { //ищем категорию в нашем массиве
poi.attributes.categories.push(wme2Gis_categories[json_poi.rubrics[0].alias]);
if (wme2GIS_debug) console.log('Subrubric found');
}
else if(json_poi.rubrics !== undefined && typeof wme2Gis_categories[rubricAlias=getRubricAlias(json_poi.rubrics[0].parent_id)] !== "undefined") { //ищем категорию родителя в нашем массиве
poi.attributes.categories.push(wme2Gis_categories[rubricAlias]);
if (wme2GIS_debug) console.log('Rubric found, ');
}
else {
poi.attributes.categories.push(wme2GIS_DefCategory);
}
if (wme2GIS_debug) console.dir(json_poi.rubrics);
if (wme2GIS_debug) console.log("json_poi.rubrics[0].alias="+json_poi.rubrics[0].alias);
var poi_name = json_poi.name;
for (var key in wme2Gis_replacement) {
poi_name = poi_name.replace(new RegExp(key,'ig'), wme2Gis_replacement[key]);
if (wme2GIS_debug) console.log("replace '"+key+"'=>'"+wme2Gis_replacement[key]+"'");
}
poi.attributes.name = poi_name;
var address=Waze.selectionManager.selectedItems[0].model.getAddress().attributes;
/* var description=((typeof json_poi.name_ex.extension !== "undefined")?json_poi.name_ex.extension:"");
if(description.length > 0)
description+=', '
*/
var description=wme2GIS_AddAddress?json_poi.address_name:"";
description+=((typeof json_poi.address_comment !== "undefined")?(description.length > 0?", ":"") + json_poi.address_comment:"");
poi.attributes.description=description;
poi.attributes.lockRank=wme2GIS_UserRank;
poi.attributes.houseNumber=address.houseNumber;
var poi_al=new wazeActionAddLandmark(poi);
Waze.model.actionManager.add(poi_al);
window.poi0=poi; // для анализа :-)
window.poi1=poi_al; // для анализа :-)
console.log(address);
// корректировка стрита - по другому пока никак :-(
var newAddressAtts={streetName: address.street.name, emptyStreet: false, cityName: address.city.attributes.name, emptyCity: false, stateID: address.state.id, countryID: address.country.id};
Waze.model.actionManager.add(new wazeActionUpdateFeatureAddress(poi, newAddressAtts, {streetIDField: 'streetID'} ));
// обеспечим автовыделение вновь созданного пои
if (!wme2GIS_dontselect) Waze.selectionManager.select([poi_al.landmark]);
if (wme2GIS_debug) console.log(json_poi.rubrics);
// сохраним информацию о пои в локальное хранилище
localStorage.setItem("wme2GIS_id_" + json_poi.id, 1);
// ставим галочку
$('[poi='+json_poi.id+']').css("display","inline-block");
}
});
}
function getRubricAlias(rubric_id) {
var rubricAlias;
var url = 'https://catalog.api.2gis.ru/2.0/catalog/rubric/get';
var data = {
"id": rubric_id,
"key": "rubnkm7490"
};
$.ajax({
dataType: "json",
cache: false,
async: false,
url: url,
data: data,
error: function() {
},
success: function(json) {
if(json.result.items[0].parent_id === undefined) {
console.log(json.result.items[0].alias);
rubricAlias = json.result.items[0].alias;
}else{
console.log('trying getRubricAlias');
getRubricAlias(json.result.items[0].parent_id);
}
}
});
return rubricAlias;
}
//******************************************************
function Wme2Gis_InitConfig()
{
if (wme2GIS_debug) console.log("Wme2Gis_InitConfig(): "+document.getElementById(CreateID()));
if(!document.getElementById(CreateID()))
{
var srsCtrl = document.createElement('section');
srsCtrl.id = CreateID();
var userTabs = document.getElementById('user-info');
if (typeof userTabs !== "undefined")
{
var navTabs = document.getElementsByClassName('nav-tabs', userTabs)[0];
if (typeof navTabs !== "undefined")
{
var tabContent = document.getElementsByClassName('tab-content', userTabs)[0];
if (typeof tabContent !== "undefined")
{
newtab = document.createElement('li');
// fa ==> http://fontawesome.io/cheatsheet/
newtab.innerHTML = '<a href="#' + CreateID() + '" id="pwme2gis" data-toggle="tab"><span class="fa fa-map-marker"></span> 2gis</a>';
navTabs.appendChild(newtab);
//srsCtrl.id = "sidepanel-???";
srsCtrl.className = "tab-pane";
var padding="padding:5px 9px";
// ------------------------------------------------------------
var srsCtrlinnerHTML = ''
+'<div class="side-panel-section">'
+'<h4>WME getting info from 2GIS <sup>' + WME_2gis_version + '</sup> <sub><a href="https://greasyfork.org/ru/scripts/19633-wme-getting-info-from-2gis" title="Link" target="_blank"><span class="fa fa-external-link"></span></a></sub></h4>'
+'<form class="attributes-form side-panel-section">'
/*
+'<div class="form-group">'
+'<label class="control-label">Категории:</label>'
+'<div class="controls">'
+'<textarea id="wme2gis_cfg_categories" style="width:100%;height:200px;font-size:8pt" wrap="off"></textarea>'
+'<small>Сопоставление: 2gis=WME, каждая пара в отдельной строке.</small>'
+'</div>'
+'</div>'
*/
+'<div class="form-group">'
+'<div class="controls">'
+'<label class="control-label" title="В какую позицию ставить новый POI">Расстановка</label>'
+'<div class="controls">'