-
Notifications
You must be signed in to change notification settings - Fork 165
/
mapnik_map.cpp
2860 lines (2588 loc) · 94.9 KB
/
mapnik_map.cpp
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
#include "mapnik_map.hpp"
#include "utils.hpp"
#include "mapnik_color.hpp" // for Color, Color::constructor
#include "mapnik_featureset.hpp" // for Featureset
#if defined(GRID_RENDERER)
#include "mapnik_grid.hpp" // for Grid, Grid::constructor
#endif
#include "mapnik_image.hpp" // for Image, Image::constructor
#include "mapnik_layer.hpp" // for Layer, Layer::constructor
#include "mapnik_palette.hpp" // for palette_ptr, Palette, etc
#include "mapnik_vector_tile.hpp"
#include "object_to_container.hpp"
// mapnik-vector-tile
#include "vector_tile_processor.hpp"
// mapnik
#include <mapnik/agg_renderer.hpp> // for agg_renderer
#include <mapnik/box2d.hpp> // for box2d
#include <mapnik/color.hpp> // for color
#include <mapnik/attribute.hpp> // for attributes
#include <mapnik/featureset.hpp> // for featureset_ptr
#if defined(GRID_RENDERER)
#include <mapnik/grid/grid.hpp> // for hit_grid, grid
#include <mapnik/grid/grid_renderer.hpp> // for grid_renderer
#endif
#include <mapnik/image.hpp> // for image_rgba8
#include <mapnik/image_any.hpp>
#include <mapnik/image_util.hpp> // for save_to_file, guess_type, etc
#include <mapnik/layer.hpp> // for layer
#include <mapnik/load_map.hpp> // for load_map, load_map_string
#include <mapnik/map.hpp> // for Map, etc
#include <mapnik/params.hpp> // for parameters
#include <mapnik/save_map.hpp> // for save_map, etc
#include <mapnik/image_scaling.hpp>
#include <mapnik/request.hpp>
#if defined(HAVE_CAIRO)
#include <mapnik/cairo_io.hpp>
#endif
// stl
#include <exception> // for exception
#include <iosfwd> // for ostringstream, ostream
#include <ostream> // for operator<<, basic_ostream, etc
#include <sstream> // for basic_ostringstream, etc
// boost
#include <boost/optional/optional.hpp> // for optional
Nan::Persistent<v8::FunctionTemplate> Map::constructor;
/**
* **`mapnik.Map`**
*
* A map in mapnik is an object that combines data sources and styles in
* a way that lets you produce styled cartographic output.
*
* @class Map
* @param {int} width in pixels
* @param {int} height in pixels
* @param {string} [projection='+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'] projection as a proj4 code
* typically used with '+init=epsg:3857'
* @property {string} src
* @property {number} width
* @property {number} height
* @property {number} bufferSize
* @property {Array<number>} extent - extent of the map as an array `[ minx, miny, maxx, maxy ]`
* @property {Array<number>} bufferedExtent - extent of the map's buffer `[ minx, miny, maxx, maxy ]`
* @property {Array<number>} maximumExtent - combination of extent and bufferedExtent `[ minx, miny, maxx, maxy ]`
* @property {mapnik.Color} background - background color as a {@link mapnik.Color} object
* @property {} parameters
* @property {} aspect_fix_mode
* @example
* var map = new mapnik.Map(25, 25, '+init=epsg:3857');
* console.log(map);
* // {
* // aspect_fix_mode: 0,
* // parameters: {},
* // background: undefined,
* // maximumExtent: undefined,
* // bufferedExtent: [ NaN, NaN, NaN, NaN ],
* // extent:
* // [ 1.7976931348623157e+308,
* // 1.7976931348623157e+308,
* // -1.7976931348623157e+308,
* // -1.7976931348623157e+308 ],
* // bufferSize: 0,
* // height: 400,
* // width: 600,
* // srs: '+init=epsg:3857'
* // }
*/
void Map::Initialize(v8::Local<v8::Object> target) {
Nan::HandleScope scope;
v8::Local<v8::FunctionTemplate> lcons = Nan::New<v8::FunctionTemplate>(Map::New);
lcons->InstanceTemplate()->SetInternalFieldCount(1);
lcons->SetClassName(Nan::New("Map").ToLocalChecked());
Nan::SetPrototypeMethod(lcons, "fonts", fonts);
Nan::SetPrototypeMethod(lcons, "fontFiles", fontFiles);
Nan::SetPrototypeMethod(lcons, "fontDirectory", fontDirectory);
Nan::SetPrototypeMethod(lcons, "loadFonts", loadFonts);
Nan::SetPrototypeMethod(lcons, "memoryFonts", memoryFonts);
Nan::SetPrototypeMethod(lcons, "registerFonts", registerFonts);
Nan::SetPrototypeMethod(lcons, "load", load);
Nan::SetPrototypeMethod(lcons, "loadSync", loadSync);
Nan::SetPrototypeMethod(lcons, "fromStringSync", fromStringSync);
Nan::SetPrototypeMethod(lcons, "fromString", fromString);
Nan::SetPrototypeMethod(lcons, "clone", clone);
Nan::SetPrototypeMethod(lcons, "save", save);
Nan::SetPrototypeMethod(lcons, "clear", clear);
Nan::SetPrototypeMethod(lcons, "toXML", toXML);
Nan::SetPrototypeMethod(lcons, "resize", resize);
Nan::SetPrototypeMethod(lcons, "render", render);
Nan::SetPrototypeMethod(lcons, "renderSync", renderSync);
Nan::SetPrototypeMethod(lcons, "renderFile", renderFile);
Nan::SetPrototypeMethod(lcons, "renderFileSync", renderFileSync);
Nan::SetPrototypeMethod(lcons, "zoomAll", zoomAll);
Nan::SetPrototypeMethod(lcons, "zoomToBox", zoomToBox); //setExtent
Nan::SetPrototypeMethod(lcons, "scale", scale);
Nan::SetPrototypeMethod(lcons, "scaleDenominator", scaleDenominator);
Nan::SetPrototypeMethod(lcons, "queryPoint", queryPoint);
Nan::SetPrototypeMethod(lcons, "queryMapPoint", queryMapPoint);
// layer access
Nan::SetPrototypeMethod(lcons, "add_layer", add_layer);
Nan::SetPrototypeMethod(lcons, "get_layer", get_layer);
Nan::SetPrototypeMethod(lcons, "layers", layers);
// properties
ATTR(lcons, "srs", get_prop, set_prop);
ATTR(lcons, "width", get_prop, set_prop);
ATTR(lcons, "height", get_prop, set_prop);
ATTR(lcons, "bufferSize", get_prop, set_prop);
ATTR(lcons, "extent", get_prop, set_prop);
ATTR(lcons, "bufferedExtent", get_prop, set_prop);
ATTR(lcons, "maximumExtent", get_prop, set_prop);
ATTR(lcons, "background", get_prop, set_prop);
ATTR(lcons, "parameters", get_prop, set_prop);
ATTR(lcons, "aspect_fix_mode", get_prop, set_prop);
NODE_MAPNIK_DEFINE_CONSTANT(lcons->GetFunction(),
"ASPECT_GROW_BBOX",mapnik::Map::GROW_BBOX)
NODE_MAPNIK_DEFINE_CONSTANT(lcons->GetFunction(),
"ASPECT_GROW_CANVAS",mapnik::Map::GROW_CANVAS)
NODE_MAPNIK_DEFINE_CONSTANT(lcons->GetFunction(),
"ASPECT_SHRINK_BBOX",mapnik::Map::SHRINK_BBOX)
NODE_MAPNIK_DEFINE_CONSTANT(lcons->GetFunction(),
"ASPECT_SHRINK_CANVAS",mapnik::Map::SHRINK_CANVAS)
NODE_MAPNIK_DEFINE_CONSTANT(lcons->GetFunction(),
"ASPECT_ADJUST_BBOX_WIDTH",mapnik::Map::ADJUST_BBOX_WIDTH)
NODE_MAPNIK_DEFINE_CONSTANT(lcons->GetFunction(),
"ASPECT_ADJUST_BBOX_HEIGHT",mapnik::Map::ADJUST_BBOX_HEIGHT)
NODE_MAPNIK_DEFINE_CONSTANT(lcons->GetFunction(),
"ASPECT_ADJUST_CANVAS_WIDTH",mapnik::Map::ADJUST_CANVAS_WIDTH)
NODE_MAPNIK_DEFINE_CONSTANT(lcons->GetFunction(),
"ASPECT_ADJUST_CANVAS_HEIGHT",mapnik::Map::ADJUST_CANVAS_HEIGHT)
NODE_MAPNIK_DEFINE_CONSTANT(lcons->GetFunction(),
"ASPECT_RESPECT",mapnik::Map::RESPECT)
target->Set(Nan::New("Map").ToLocalChecked(),lcons->GetFunction());
constructor.Reset(lcons);
}
Map::Map(int width, int height) :
Nan::ObjectWrap(),
map_(std::make_shared<mapnik::Map>(width,height)),
in_use_(false) {}
Map::Map(int width, int height, std::string const& srs) :
Nan::ObjectWrap(),
map_(std::make_shared<mapnik::Map>(width,height,srs)),
in_use_(false) {}
Map::Map() :
Nan::ObjectWrap(),
map_(),
in_use_(false) {}
Map::~Map() { }
bool Map::acquire() {
if (in_use_)
{
return false;
}
in_use_ = true;
return true;
}
void Map::release() {
in_use_ = false;
}
NAN_METHOD(Map::New)
{
if (!info.IsConstructCall())
{
Nan::ThrowError("Cannot call constructor as function, you need to use 'new' keyword");
return;
}
// accept a reference or v8:External?
if (info[0]->IsExternal())
{
v8::Local<v8::External> ext = info[0].As<v8::External>();
void* ptr = ext->Value();
Map* m = static_cast<Map*>(ptr);
m->Wrap(info.This());
info.GetReturnValue().Set(info.This());
return;
}
if (info.Length() == 2)
{
if (!info[0]->IsNumber() || !info[1]->IsNumber())
{
Nan::ThrowTypeError("'width' and 'height' must be integers");
return;
}
Map* m = new Map(info[0]->IntegerValue(),info[1]->IntegerValue());
m->Wrap(info.This());
info.GetReturnValue().Set(info.This());
return;
}
else if (info.Length() == 3)
{
if (!info[0]->IsNumber() || !info[1]->IsNumber())
{
Nan::ThrowTypeError("'width' and 'height' must be integers");
return;
}
if (!info[2]->IsString())
{
Nan::ThrowError("'srs' value must be a string");
return;
}
Map* m = new Map(info[0]->IntegerValue(), info[1]->IntegerValue(), TOSTR(info[2]));
m->Wrap(info.This());
info.GetReturnValue().Set(info.This());
return;
}
else
{
Nan::ThrowError("please provide Map width and height and optional srs");
return;
}
return;
}
NAN_GETTER(Map::get_prop)
{
Map* m = Nan::ObjectWrap::Unwrap<Map>(info.Holder());
std::string a = TOSTR(property);
if(a == "extent") {
v8::Local<v8::Array> arr = Nan::New<v8::Array>(4);
mapnik::box2d<double> const& e = m->map_->get_current_extent();
arr->Set(0, Nan::New<v8::Number>(e.minx()));
arr->Set(1, Nan::New<v8::Number>(e.miny()));
arr->Set(2, Nan::New<v8::Number>(e.maxx()));
arr->Set(3, Nan::New<v8::Number>(e.maxy()));
info.GetReturnValue().Set(arr);
}
else if(a == "bufferedExtent") {
boost::optional<mapnik::box2d<double> > const& e = m->map_->get_buffered_extent();
v8::Local<v8::Array> arr = Nan::New<v8::Array>(4);
arr->Set(0, Nan::New<v8::Number>(e->minx()));
arr->Set(1, Nan::New<v8::Number>(e->miny()));
arr->Set(2, Nan::New<v8::Number>(e->maxx()));
arr->Set(3, Nan::New<v8::Number>(e->maxy()));
info.GetReturnValue().Set(arr);
}
else if(a == "maximumExtent") {
boost::optional<mapnik::box2d<double> > const& e = m->map_->maximum_extent();
if (!e)
return;
v8::Local<v8::Array> arr = Nan::New<v8::Array>(4);
arr->Set(0, Nan::New<v8::Number>(e->minx()));
arr->Set(1, Nan::New<v8::Number>(e->miny()));
arr->Set(2, Nan::New<v8::Number>(e->maxx()));
arr->Set(3, Nan::New<v8::Number>(e->maxy()));
info.GetReturnValue().Set(arr);
}
else if(a == "aspect_fix_mode")
info.GetReturnValue().Set(Nan::New<v8::Integer>(m->map_->get_aspect_fix_mode()));
else if(a == "width")
info.GetReturnValue().Set(Nan::New<v8::Integer>(m->map_->width()));
else if(a == "height")
info.GetReturnValue().Set(Nan::New<v8::Integer>(m->map_->height()));
else if (a == "srs")
info.GetReturnValue().Set(Nan::New<v8::String>(m->map_->srs()).ToLocalChecked());
else if(a == "bufferSize")
info.GetReturnValue().Set(Nan::New<v8::Integer>(m->map_->buffer_size()));
else if (a == "background") {
boost::optional<mapnik::color> c = m->map_->background();
if (c)
info.GetReturnValue().Set(Color::NewInstance(*c));
else
return;
}
else //if (a == "parameters")
{
v8::Local<v8::Object> ds = Nan::New<v8::Object>();
mapnik::parameters const& params = m->map_->get_extra_parameters();
mapnik::parameters::const_iterator it = params.begin();
mapnik::parameters::const_iterator end = params.end();
for (; it != end; ++it)
{
node_mapnik::params_to_object(ds, it->first, it->second);
}
info.GetReturnValue().Set(ds);
}
}
NAN_SETTER(Map::set_prop)
{
Map* m = Nan::ObjectWrap::Unwrap<Map>(info.Holder());
std::string a = TOSTR(property);
if(a == "extent" || a == "maximumExtent") {
if (!value->IsArray()) {
Nan::ThrowError("Must provide an array of: [minx,miny,maxx,maxy]");
return;
} else {
v8::Local<v8::Array> arr = value.As<v8::Array>();
if (arr->Length() != 4) {
Nan::ThrowError("Must provide an array of: [minx,miny,maxx,maxy]");
return;
} else {
double minx = arr->Get(0)->NumberValue();
double miny = arr->Get(1)->NumberValue();
double maxx = arr->Get(2)->NumberValue();
double maxy = arr->Get(3)->NumberValue();
mapnik::box2d<double> box(minx,miny,maxx,maxy);
if(a == "extent")
m->map_->zoom_to_box(box);
else
m->map_->set_maximum_extent(box);
}
}
}
else if (a == "aspect_fix_mode")
{
if (!value->IsNumber()) {
Nan::ThrowError("'aspect_fix_mode' must be a constant (number)");
return;
} else {
int val = value->IntegerValue();
if (val < mapnik::Map::aspect_fix_mode_MAX && val >= 0) {
m->map_->set_aspect_fix_mode(static_cast<mapnik::Map::aspect_fix_mode>(val));
} else {
Nan::ThrowError("'aspect_fix_mode' value is invalid");
return;
}
}
}
else if (a == "srs")
{
if (!value->IsString()) {
Nan::ThrowError("'srs' must be a string");
return;
} else {
m->map_->set_srs(TOSTR(value));
}
}
else if (a == "bufferSize") {
if (!value->IsNumber()) {
Nan::ThrowTypeError("Must provide an integer bufferSize");
return;
} else {
m->map_->set_buffer_size(value->IntegerValue());
}
}
else if (a == "width") {
if (!value->IsNumber()) {
Nan::ThrowTypeError("Must provide an integer width");
return;
} else {
m->map_->set_width(value->IntegerValue());
}
}
else if (a == "height") {
if (!value->IsNumber()) {
Nan::ThrowTypeError("Must provide an integer height");
return;
} else {
m->map_->set_height(value->IntegerValue());
}
}
else if (a == "background") {
if (!value->IsObject()) {
Nan::ThrowTypeError("mapnik.Color expected");
return;
}
v8::Local<v8::Object> obj = value.As<v8::Object>();
if (obj->IsNull() || obj->IsUndefined() || !Nan::New(Color::constructor)->HasInstance(obj)) {
Nan::ThrowTypeError("mapnik.Color expected");
return;
}
Color *c = Nan::ObjectWrap::Unwrap<Color>(obj);
m->map_->set_background(*c->get());
}
else if (a == "parameters") {
if (!value->IsObject()) {
Nan::ThrowTypeError("object expected for map.parameters");
return;
}
v8::Local<v8::Object> obj = value->ToObject();
mapnik::parameters params;
v8::Local<v8::Array> names = obj->GetPropertyNames();
unsigned int i = 0;
unsigned int a_length = names->Length();
while (i < a_length) {
v8::Local<v8::Value> name = names->Get(i)->ToString();
v8::Local<v8::Value> a_value = obj->Get(name);
if (a_value->IsString()) {
params[TOSTR(name)] = const_cast<char const*>(TOSTR(a_value));
} else if (a_value->IsNumber()) {
double num = a_value->NumberValue();
// todo - round
if (num == a_value->IntegerValue()) {
params[TOSTR(name)] = static_cast<node_mapnik::value_integer>(a_value->IntegerValue());
} else {
double dub_val = a_value->NumberValue();
params[TOSTR(name)] = dub_val;
}
} else if (a_value->IsBoolean()) {
params[TOSTR(name)] = static_cast<mapnik::value_bool>(a_value->BooleanValue());
}
i++;
}
m->map_->set_extra_parameters(params);
}
}
/**
* Load fonts from local or external source
*
* @name loadFonts
* @memberof Map
* @instance
*
*/
NAN_METHOD(Map::loadFonts)
{
Map* m = Nan::ObjectWrap::Unwrap<Map>(info.Holder());
info.GetReturnValue().Set(Nan::New<v8::Boolean>(m->map_->load_fonts()));
}
NAN_METHOD(Map::memoryFonts)
{
Map* m = Nan::ObjectWrap::Unwrap<Map>(info.Holder());
auto const& font_cache = m->map_->get_font_memory_cache();
v8::Local<v8::Array> a = Nan::New<v8::Array>(font_cache.size());
unsigned i = 0;
for (auto const& kv : font_cache)
{
a->Set(i++, Nan::New(kv.first).ToLocalChecked());
}
info.GetReturnValue().Set(a);
}
NAN_METHOD(Map::registerFonts)
{
Map* m = Nan::ObjectWrap::Unwrap<Map>(info.Holder());
if (info.Length() == 0 || !info[0]->IsString())
{
Nan::ThrowTypeError("first argument must be a path to a directory of fonts");
return;
}
bool recurse = false;
if (info.Length() >= 2)
{
if (!info[1]->IsObject())
{
Nan::ThrowTypeError("second argument is optional, but if provided must be an object, eg. { recurse: true }");
return;
}
v8::Local<v8::Object> options = info[1].As<v8::Object>();
if (options->Has(Nan::New("recurse").ToLocalChecked()))
{
v8::Local<v8::Value> recurse_opt = options->Get(Nan::New("recurse").ToLocalChecked());
if (!recurse_opt->IsBoolean())
{
Nan::ThrowTypeError("'recurse' must be a Boolean");
return;
}
recurse = recurse_opt->BooleanValue();
}
}
std::string path = TOSTR(info[0]);
info.GetReturnValue().Set(Nan::New(m->map_->register_fonts(path,recurse)));
}
/**
* Get all of the fonts currently registered as part of this map
* @memberof Map
* @instance
* @name font
* @returns {Array<string>} fonts
*/
NAN_METHOD(Map::fonts)
{
Map* m = Nan::ObjectWrap::Unwrap<Map>(info.Holder());
auto const& mapping = m->map_->get_font_file_mapping();
v8::Local<v8::Array> a = Nan::New<v8::Array>(mapping.size());
unsigned i = 0;
for (auto const& kv : mapping)
{
a->Set(i++, Nan::New<v8::String>(kv.first).ToLocalChecked());
}
info.GetReturnValue().Set(a);
}
/**
* Get all of the fonts currently registered as part of this map, as a mapping
* from font to font file
* @memberof Map
* @instance
* @name fontFiles
* @returns {Object} fonts
*/
NAN_METHOD(Map::fontFiles)
{
Map* m = Nan::ObjectWrap::Unwrap<Map>(info.Holder());
auto const& mapping = m->map_->get_font_file_mapping();
v8::Local<v8::Object> obj = Nan::New<v8::Object>();
for (auto const& kv : mapping)
{
obj->Set(Nan::New<v8::String>(kv.first).ToLocalChecked(), Nan::New<v8::String>(kv.second.second).ToLocalChecked());
}
info.GetReturnValue().Set(obj);
}
/**
* Get the currently-registered font directory, if any
* @memberof Map
* @instance
* @name fontDirectory
* @returns {string|undefined} fonts
*/
NAN_METHOD(Map::fontDirectory)
{
Map* m = Nan::ObjectWrap::Unwrap<Map>(info.Holder());
boost::optional<std::string> const& fdir = m->map_->font_directory();
if (fdir)
{
info.GetReturnValue().Set(Nan::New<v8::String>(*fdir).ToLocalChecked());
}
return;
}
/**
* Get the map's scale factor. This is the ratio between pixels and geographical
* units like meters.
* @memberof Map
* @instance
* @name scale
* @returns {number} scale
*/
NAN_METHOD(Map::scale)
{
Map* m = Nan::ObjectWrap::Unwrap<Map>(info.Holder());
info.GetReturnValue().Set(Nan::New<v8::Number>(m->map_->scale()));
}
/**
* Get the map's scale denominator.
*
* @memberof Map
* @instance
* @name scaleDenominator
* @returns {number} scale denominator
*/
NAN_METHOD(Map::scaleDenominator)
{
Map* m = Nan::ObjectWrap::Unwrap<Map>(info.Holder());
info.GetReturnValue().Set(Nan::New<v8::Number>(m->map_->scale_denominator()));
}
typedef struct {
uv_work_t request;
Map *m;
std::map<std::string,mapnik::featureset_ptr> featuresets;
int layer_idx;
bool geo_coords;
double x;
double y;
bool error;
std::string error_name;
Nan::Persistent<v8::Function> cb;
} query_map_baton_t;
/**
* Query a `Mapnik#Map` object to retrieve layer and feature data based on an
* X and Y `Mapnik#Map` coordinates (use `Map#queryPoint` to query with geographic coordinates).
*
* @name queryMapPoint
* @memberof Map
* @instance
* @param {number} x - x coordinate
* @param {number} y - y coordinate
* @param {Object} [options]
* @param {String|number} [options.layer] - layer name (string) or index (positive integer, 0 index)
* to query. If left blank, will query all layers.
* @param {Function} callback
* @returns {Array} array - An array of `Featureset` objects and layer names, which each contain their own
* `Feature` objects.
* @example
* // iterate over the first layer returned and get all attribute information for each feature
* map.queryMapPoint(10, 10, {layer: 0}, function(err, results) {
* if (err) throw err;
* console.log(results); // => [{"layer":"layer_name","featureset":{}}]
* var featureset = results[0].featureset;
* var attributes = [];
* var feature;
* while ((feature = featureset.next())) {
* attributes.push(feature.attributes());
* }
* console.log(attributes); // => [{"attr_key": "attr_value"}, {...}, {...}]
* });
*
*/
NAN_METHOD(Map::queryMapPoint)
{
abstractQueryPoint(info,false);
return;
}
/**
* Query a `Mapnik#Map` object to retrieve layer and feature data based on geographic
* coordinates of the source data (use `Map#queryMapPoint` to query with XY coordinates).
*
* @name queryPoint
* @memberof Map
* @instance
* @param {number} x - x geographic coordinate (CRS based on source data)
* @param {number} y - y geographic coordinate (CRS based on source data)
* @param {Object} [options]
* @param {String|number} [options.layer] - layer name (string) or index (positive integer, 0 index)
* to query. If left blank, will query all layers.
* @param {Function} callback
* @returns {Array} array - An array of `Featureset` objects and layer names, which each contain their own
* `Feature` objects.
* @example
* // query based on web mercator coordinates
* map.queryMapPoint(-12957605.0331, 5518141.9452, {layer: 0}, function(err, results) {
* if (err) throw err;
* console.log(results); // => [{"layer":"layer_name","featureset":{}}]
* var featureset = results[0].featureset;
* var attributes = [];
* var feature;
* while ((feature = featureset.next())) {
* attributes.push(feature.attributes());
* }
* console.log(attributes); // => [{"attr_key": "attr_value"}, {...}, {...}]
* });
*
*/
NAN_METHOD(Map::queryPoint)
{
abstractQueryPoint(info,true);
return;
}
v8::Local<v8::Value> Map::abstractQueryPoint(Nan::NAN_METHOD_ARGS_TYPE info, bool geo_coords)
{
Nan::HandleScope scope;
if (info.Length() < 3)
{
Nan::ThrowError("requires at least three arguments, a x,y query and a callback");
return Nan::Undefined();
}
double x,y;
if (!info[0]->IsNumber() || !info[1]->IsNumber())
{
Nan::ThrowTypeError("x,y arguments must be numbers");
return Nan::Undefined();
}
else
{
x = info[0]->NumberValue();
y = info[1]->NumberValue();
}
Map* m = Nan::ObjectWrap::Unwrap<Map>(info.Holder());
v8::Local<v8::Object> options = Nan::New<v8::Object>();
int layer_idx = -1;
if (info.Length() > 3)
{
// options object
if (!info[2]->IsObject()) {
Nan::ThrowTypeError("optional third argument must be an options object");
return Nan::Undefined();
}
options = info[2]->ToObject();
if (options->Has(Nan::New("layer").ToLocalChecked()))
{
std::vector<mapnik::layer> const& layers = m->map_->layers();
v8::Local<v8::Value> layer_id = options->Get(Nan::New("layer").ToLocalChecked());
if (! (layer_id->IsString() || layer_id->IsNumber()) ) {
Nan::ThrowTypeError("'layer' option required for map query and must be either a layer name(string) or layer index (integer)");
return Nan::Undefined();
}
if (layer_id->IsString()) {
bool found = false;
unsigned int idx(0);
std::string layer_name = TOSTR(layer_id);
for (mapnik::layer const& lyr : layers)
{
if (lyr.name() == layer_name)
{
found = true;
layer_idx = idx;
break;
}
++idx;
}
if (!found)
{
std::ostringstream s;
s << "Layer name '" << layer_name << "' not found";
Nan::ThrowTypeError(s.str().c_str());
return Nan::Undefined();
}
}
else if (layer_id->IsNumber())
{
layer_idx = layer_id->IntegerValue();
std::size_t layer_num = layers.size();
if (layer_idx < 0) {
std::ostringstream s;
s << "Zero-based layer index '" << layer_idx << "' not valid"
<< " must be a positive integer, ";
if (layer_num > 0)
{
s << "only '" << layer_num << "' layers exist in map";
}
else
{
s << "no layers found in map";
}
Nan::ThrowTypeError(s.str().c_str());
return Nan::Undefined();
} else if (layer_idx >= static_cast<int>(layer_num)) {
std::ostringstream s;
s << "Zero-based layer index '" << layer_idx << "' not valid, ";
if (layer_num > 0)
{
s << "only '" << layer_num << "' layers exist in map";
}
else
{
s << "no layers found in map";
}
Nan::ThrowTypeError(s.str().c_str());
return Nan::Undefined();
}
}
}
}
// ensure function callback
v8::Local<v8::Value> callback = info[info.Length() - 1];
if (!callback->IsFunction()) {
Nan::ThrowTypeError("last argument must be a callback function");
return Nan::Undefined();
}
query_map_baton_t *closure = new query_map_baton_t();
closure->request.data = closure;
closure->m = m;
closure->x = x;
closure->y = y;
closure->layer_idx = static_cast<std::size_t>(layer_idx);
closure->geo_coords = geo_coords;
closure->error = false;
closure->cb.Reset(callback.As<v8::Function>());
uv_queue_work(uv_default_loop(), &closure->request, EIO_QueryMap, (uv_after_work_cb)EIO_AfterQueryMap);
m->Ref();
return Nan::Undefined();
}
void Map::EIO_QueryMap(uv_work_t* req)
{
query_map_baton_t *closure = static_cast<query_map_baton_t *>(req->data);
try
{
std::vector<mapnik::layer> const& layers = closure->m->map_->layers();
if (closure->layer_idx >= 0)
{
mapnik::featureset_ptr fs;
if (closure->geo_coords)
{
fs = closure->m->map_->query_point(closure->layer_idx,
closure->x,
closure->y);
}
else
{
fs = closure->m->map_->query_map_point(closure->layer_idx,
closure->x,
closure->y);
}
mapnik::layer const& lyr = layers[closure->layer_idx];
closure->featuresets.insert(std::make_pair(lyr.name(),fs));
}
else
{
// query all layers
unsigned idx = 0;
for (mapnik::layer const& lyr : layers)
{
mapnik::featureset_ptr fs;
if (closure->geo_coords)
{
fs = closure->m->map_->query_point(idx,
closure->x,
closure->y);
}
else
{
fs = closure->m->map_->query_map_point(idx,
closure->x,
closure->y);
}
closure->featuresets.insert(std::make_pair(lyr.name(),fs));
++idx;
}
}
}
catch (std::exception const& ex)
{
closure->error = true;
closure->error_name = ex.what();
}
}
void Map::EIO_AfterQueryMap(uv_work_t* req)
{
Nan::HandleScope scope;
query_map_baton_t *closure = static_cast<query_map_baton_t *>(req->data);
if (closure->error) {
v8::Local<v8::Value> argv[1] = { Nan::Error(closure->error_name.c_str()) };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv);
} else {
std::size_t num_result = closure->featuresets.size();
if (num_result >= 1)
{
v8::Local<v8::Array> a = Nan::New<v8::Array>(num_result);
typedef std::map<std::string,mapnik::featureset_ptr> fs_itr;
fs_itr::const_iterator it = closure->featuresets.begin();
fs_itr::const_iterator end = closure->featuresets.end();
unsigned idx = 0;
for (; it != end; ++it)
{
v8::Local<v8::Object> obj = Nan::New<v8::Object>();
obj->Set(Nan::New("layer").ToLocalChecked(), Nan::New<v8::String>(it->first).ToLocalChecked());
obj->Set(Nan::New("featureset").ToLocalChecked(), Featureset::NewInstance(it->second));
a->Set(idx, obj);
++idx;
}
closure->featuresets.clear();
v8::Local<v8::Value> argv[2] = { Nan::Null(), a };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 2, argv);
}
else
{
v8::Local<v8::Value> argv[2] = { Nan::Null(), Nan::Undefined() };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 2, argv);
}
}
closure->m->Unref();
closure->cb.Reset();
delete closure;
}
/**
* Get all of the currently-added layers in this map
*
* @memberof Map
* @instance
* @name layers
* @returns {Array<mapnik.Layer>} layers
*/
NAN_METHOD(Map::layers)
{
Map* m = Nan::ObjectWrap::Unwrap<Map>(info.Holder());
std::vector<mapnik::layer> const& layers = m->map_->layers();
v8::Local<v8::Array> a = Nan::New<v8::Array>(layers.size());
for (unsigned i = 0; i < layers.size(); ++i )
{
a->Set(i, Layer::NewInstance(layers[i]));
}
info.GetReturnValue().Set(a);
}
/**
* Add a new layer to this map
*
* @memberof Map
* @instance
* @name add_layer
* @param {mapnik.Layer} new layer
*/
NAN_METHOD(Map::add_layer) {
if (!info[0]->IsObject()) {
Nan::ThrowTypeError("mapnik.Layer expected");
return;
}
v8::Local<v8::Object> obj = info[0].As<v8::Object>();
if (obj->IsNull() || obj->IsUndefined() || !Nan::New(Layer::constructor)->HasInstance(obj)) {
Nan::ThrowTypeError("mapnik.Layer expected");
return;
}
Layer *l = Nan::ObjectWrap::Unwrap<Layer>(obj);
Map* m = Nan::ObjectWrap::Unwrap<Map>(info.Holder());
m->map_->add_layer(*l->get());
return;
}
/**
* Get a layer out of this map, given a name or index
*
* @memberof Map
* @instance
* @name get_layer
* @param {string|number} layer name or index
* @returns {mapnik.Layer} the layer
* @throws {Error} if index is incorrect or layer is not found
*/
NAN_METHOD(Map::get_layer)
{
if (info.Length() != 1) {
Nan::ThrowError("Please provide layer name or index");
return;
}
Map* m = Nan::ObjectWrap::Unwrap<Map>(info.Holder());
std::vector<mapnik::layer> const& layers = m->map_->layers();
v8::Local<v8::Value> layer = info[0];
if (layer->IsNumber())
{
unsigned int index = info[0]->IntegerValue();
if (index < layers.size())
{
info.GetReturnValue().Set(Layer::NewInstance(layers[index]));
return;
}
else
{
Nan::ThrowTypeError("invalid layer index");
return;
}
}
else if (layer->IsString())
{
bool found = false;
unsigned int idx(0);
std::string layer_name = TOSTR(layer);
for ( mapnik::layer const& lyr : layers)
{
if (lyr.name() == layer_name)
{
found = true;
info.GetReturnValue().Set(Layer::NewInstance(layers[idx]));
return;
}
++idx;
}
if (!found)
{
std::ostringstream s;
s << "Layer name '" << layer_name << "' not found";
Nan::ThrowTypeError(s.str().c_str());
return;
}
}
Nan::ThrowTypeError("first argument must be either a layer name(string) or layer index (integer)");
return;