forked from toepoke/mapsed
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mapsed.js
1872 lines (1546 loc) · 55 KB
/
mapsed.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
/*jslint passfail: true, nomen: true, vars: true, white: true, indent: 2, maxerr: 999 */
/*
* Developed by : www.toepoke.co.uk
*
* If you redistribute this file, please keep this section in place
*
* License: Same as jQuery - see http://jquery.org/license
*
* Compressed with:
* - http://closure-compiler.appspot.com/
*
*/
(function () {
// http://www.yuiblog.com/blog/2010/12/14/strict-mode-is-coming-to-town/
"use strict";
// singleton here (same variable across all instances of the plug-in)
var _version = '(0.3)',
_plugInName = "mapsed",
_plugInInstances = 1
;
$.fn.mapsed = function (options) {
// consts
// - Centre of the UK (ish ...)
var DEFAULT_CENTER = new google.maps.LatLng(53.175148, -1.423908);
var DEFAULT_ZOOM = 10;
// private plug-in variables
var _plugIn = this, // Reference back to the "mapsed" plug-in instance
_searchBox = null, // Search box that appears on the map
_gmSearchBox = null, // Google (autocompleting) Search box the underlying input text box is twinned with
_searchBtn = null, // Button to click to confirm search should be applied (not strictly needed (ENTER does the same), but users may be confused if there isn't one!)
_moreBtn = null, // Available when more results are available for a result set (Google Places API pages the results)
_pageNum = 0, // Keeps track of how many pages of results are shown (used to reset the markers on a new search)
_gMap = null, // Underlying Google maps object for the div
_mapContainer = null, // jQuery reference to the DIV the map is in
_placesApi = null, // Reference to the Google Places API object
_markers = [], // Set of markers displayed on the map
_instance = -1, // Instance "this" plug-in is managing (so we can support zmultiple maps on the page)
_fullWin = false, // Flags "mapsed" is in full-window mode, which means "mapsed" created the DIV we're in
_firstSearch = true, // Used to ensure we don't clear markers when the map is drawn for the first time (so any "showOnLoad" markers aren't cleared)
_hasMapInitFired = false, // Used to flag initialisation of the map (after Google Maps API has finished drawing it)
_areBoundsSet = false, // Used to flag that an event has set the boundary (so we don't set the zoom/center manually as GM will calc this for us)
_helpBtn = null, // Reference to the help dialog button ([?])
_helpDlg = null, // Reference to the help dialog that is toggled by the help button
_closeBtn = null, // Reference to the close button (only used in full-window mode)
_addBtn = null, // Reference to the add button ([+])
_geoBtn = null, // Reference to the Geo location button [(*)]
gm = null, // Short cut reference to the Google Maps namespace (this is initialised in the constructor to give the Google API time to load on the page)
gp = null // Short cut reference to the Google Places namespace (this is initialised in the constructor to give the Google API time to load on the page)
;
/// <summary>
/// Plug-in options:
/// Set of options to configure how the map will behave
/// </summary>
var settings = $.extend({
// Array of places to show on the map initially
// (see accompanying examples for illustration)
showOnLoad: null,
// Specifies the buttons and tooltips added to the map toolbar
ToolbarButtons: {
Go: "Go",
More: "More|There are more results available ...",
AddPlace: "+|Add a place",
CloseMap: "×|Close map",
Geo: "⊗|Centre map based on your location",
Help: "?|Show help"
},
// Species the text of the buttons used the dialog templates
ActionButtons: {
Select: "Select",
Edit: "Edit",
Delete: "Delete",
Save: "Save"
},
// Options for drawing the map. This is the same object
// that is passed to the Google Maps API when creating the map.
// If you need something custom supported by the Google Maps API
// you should be able to add in your own initialisation code
// to this object.
mapOptions: {
// Initial zoom level (initially not set)
// ... be cautious when setting a zoom level _and_ defining custom places as you may set the
// ... level to such a level that your places aren't visible
// ... by default the map will expand to show all custom places, you can change this with the "forceCenter" option
zoom: DEFAULT_ZOOM,
// Default to the best theatre ever :-)
center: DEFAULT_CENTER,
// Type of map to show initially
mapTypeId: google.maps.MapTypeId.ROADMAP
},
// Flags whether Google Maps should still display other points-of-interest
// By default POI is enabled because the POIs can't be turned off when using custom styled maps
// (well without significant hacks!)
// If you require custom maps, you need "disablePoi" set to false
disablePoi: false,
// Flags that the user can add new places (as well as edit/delete), an "+" icon appears
// at the top right of the map
allowAdd: false,
searchOptions: {
// Flags that the user can search for places themselves
// ... adds a search box to the map
enabled: false,
// Placeholder text for the search box
placeholder: "e.g. Hotels in Leeds",
// Initialises the place search with a given text search
// ... (i.e. once the map has been created, the results for this string are also shown)
initSearch: "Hotels in Leeds",
// Performs a search when geo-location is activated. This can be either
// on load (see "findGeoOnLoad" option) or when the Geo location button is clicked
// {POSITION} is replaced with the detected Geo location position
// "geoSearch" supersedes any "initSearch" specified (if the user enables Geo location for the map)
geoSearch: "5aside football near {POSITION}"
},
// Event when user clicks the "Select" button
// prototype: function(mapsed, details)
onSelect: null,
// Allows new places to be edited
// prototype: function(mapsed, newPlace)
// return a error message string if you're not happy with what's been entered
// return an empty string to confirm it's been saved
onSave: null,
// Allows the user to delete a "custom" map they've previously added
// prototype: function(mapsed, details)
// return true to confirm delete, false abandons the delete
onDelete: null,
// Flags that the user is asked for confirmation if they try and
// delete a place
confirmDelete: false,
// Event fires when user clicks the "X" button (only in full window mode)
// prototype: function(mapsed)
// return true to close the map, false keeps it open
onClose: null,
// Callback for getting the [image] URL to use for a marker
// Parameter "markerType" is passed, indicating the type of marker, this can be
// prototype: function(mapsed, markerType, title)
// Parameters:
// mapsed: Reference to the mapsed plugin
// markerType: The type of marker being added to the map:
// "new" = Marker created using the "+" button to add a new place
// "google" = Marker is being added from a Google Places place
// "custom" = Marker is being added from application database (via "showOnLoad" array)
// title: Title attribute of the marker
// Returns:
// Google Icon object (see https://developers.google.com/maps/documentation/javascript/reference#Icon)
getMarkerImage: null,
// Adds a help button to give further instructions to the end user
// prototype: function()
getHelpWindow: null,
// show the help dialog when the map is loaded
showHelpOnLoad: false,
// Adds a GEO location button onto the map which is used to set the
// centre of the map according to the user's GEO location position
allowGeo: false,
// Flags that mapsed should place the centre of the map where the user's
// GEO location position is.
// Note: This is ignored if "showOnLoad" property is populated as there is
// a risk the places won't be shown on the map
findGeoOnLoad: false,
// When adding custom places, mapsed will expand the map to show all places
// Usually this is what you'd want, but sometimes you may want to focus on a particular area
// "forceCenter" will override the default behaviour and centre where specified in the options
forceCenter: false
}, options || {});
//
// PUBLIC METHODS
//
/// <summary>
/// Get the settings the map was build with
/// </summary>
this.getSettings = function () {
return settings;
};
/// <summary>
/// Gets the underlying Google Map object that was initially
/// created
/// - useful if you want to play directly with the map to provide
/// further functionality outside mapsed
/// </summary>
this.getGoogleMap = function () {
return _gMap;
};
/// <summary>
/// Usually you'll already know this (it's how you called up
/// the mapsed jQuery plugin - however in full-window mode the div is
/// generated, so you'll need this then ... sometimes :-)
/// - see "onPreInit" full-window example.
/// </summary>
this.getMapContainer = function () {
return _mapContainer;
};
/// <summary>
/// Helper method to make it a bit easier to add your own controls onto
/// the map.
/// markUp - HTML for the control (just HTML, no jQuery or anything, ID is _not_ required)
/// ctrlPos - Where on the map the control should be added, available options details here:
/// https://developers.google.com/maps/documentation/javascript/controls#ControlPositioning
/// </summary>
this.addMapControl = function (markUp, ctrlPos) {
var $control = null,
$html = null
;
// create a jQuery object out of the markup
$html = $(markUp);
// add control into the DOM
// ... (as part of the map container as the control is "owned" by the map)
$control = $html.appendTo(_mapContainer);
// tell Google Maps where to place it
_gMap.controls[ctrlPos].push($control[0]);
// and return the create control so the events can be wired up
return $control;
};
/// <summary>
/// Turns off clicking of Google places of interest.
/// Note this turns off ALL styling so don't use this option
/// when using custom styles.
/// </summary>
this.disablePointsOfInterest = function () {
_gMap.styles =
[
{
featureType: "poi",
stylers: [
{ visibility: "off" }
]
}
];
},
/// <summary>
/// When in full-window mode, this will close the map
/// and release resources.
/// </summary>
this.closeMap = function () {
// just kill the DIV container and Google object
_gMap = null;
// close help dialog (if displayed)
if (_helpDlg) {
_helpDlg.fadeOut();
}
// close if only available if we created the DIV and we're in full screen mode
// so kill off the DIV and remove
_mapContainer.fadeOut(function () {
$(this).remove();
});
// no longer in full window mode
_fullWin = false;
} // closeMap
/// <summary>
/// Displays a modal message over the top of the map
/// title - text to appear in the title bar
/// msg - text to appear as the main message
/// callback - callback function to call when OK is clicked
/// </summary>
this.showMsg = function (title, msg, callback) {
buildMsg(title, msg, false/*doConfirm*/, "", callback);
}
/// <summary>
/// Displays the "Add" dialog once the calling application
/// has resolved what should be displayed for the new marker
/// </summary>
this.showAddDialog = function (marker) {
// new places can always be edited
marker.showTooltip(true/*inRwMode*/);
}
/// <summary>
/// Displays a modal confirmation over the top of the map, prompting
/// the user to "confirm" _some_ action
/// title - text to appear in the title bar
/// msg - text to appear as the main message
/// prompt - text to appear next to the action buttons
/// callback - callback function to call when OK is clicked
/// Note the callback is ONLY called when OK is clicked
/// </summary>
this.confirmMsg = function (title, msg, prompt, callback) {
buildMsg(title, msg, true/*doConfirm*/, prompt, callback);
}
/// <summary>
/// Moves the map location to the centre of the geo-location of the user
/// If custom places are defined, these are also added.
/// Note: Custom places are only added when the map is first loaded
/// If the user clicks the geo-button the custom places aren't added as the "geoSearch"
/// takes priority, overwriting the "showOnLoad" places (due to order of the callbacks)
/// </summary>
this.setMapCentreByGeo = function () {
if (!navigator.geolocation)
// GEO location not supported
return;
navigator.geolocation.getCurrentPosition(
function (geoPos) {
var pos = new gm.LatLng(geoPos.coords.latitude, geoPos.coords.longitude);
_gMap.setZoom(10);
_gMap.setCenter(pos);
// change geo button to show it's now active
_geoBtn.addClass("is-active");
// first time map has been loaded, so apply any initial search
var so = settings.searchOptions;
if (so && so.geoSearch && so.geoSearch.length > 0) {
var newLocation = pos.toUrlValue();
var search = so.geoSearch.replace("{POSITION}", newLocation);
doSearch(search);
}
if (so && settings.showOnLoad) {
addInitialPlaces();
}
},
function (err) {
_plugIn.showMsg("GEO Position", err.message);
}
);
}
//
// MAPSED EVENT HANDLERS
// - Handlers for mapsed events. Typically these will issue
// callbacks to the calling application (see events in the settings above)
//
/// <summary>
/// Internal event handler when the "Select" button is clicked
/// - Builds the model and forwards onto the callback for confirmation
/// </summary>
function onPlaceSelect(element) {
var $root = element.parents(".mapsed-root");
var $vw = element.parents(".mapsed-view");
var model = getViewModel($vw);
if (settings.onSelect(_plugIn, model)) {
closeTooltips();
}
} // onPlaceSelect
/// <summary>
/// Internal event handler when the "Edit" button is clicked
/// - Swaps the tooltip to edit mode, prompting for data entry
/// </summary>
function onPlaceEdit(element) {
var $root = element.parents(".mapsed-root");
var lat = $root.find(".mapsed-lat").val();
var lng = $root.find(".mapsed-lng").val();
// find the appropriate marker
var marker = findMarker(lat, lng);
// close any open tooltips so the user can concentrate on editing
closeTooltips();
// user clicks the edit button, so swap to edit mode
marker.showTooltip(true/*inRwMode*/);
} // onPlaceEdit
/// <summary>
/// Internal event handler when the "Add" button is clicked
/// </summary>
function onPlaceAdd(evt) {
evt.preventDefault();
var centre = _gMap.getCenter();
var bounds = new gm.LatLngBounds();
var newMarker = createMarker("New place", centre, true/*draggable*/, "new");
attachTooltip(newMarker);
_markers.push(newMarker);
bounds.extend(centre);
gm.event.addListener(newMarker, "click", function (evt) {
var currMarker = this;
closeTooltips();
if (settings.onAdd) {
var root = $(currMarker.tooltip.content);
settings.onAdd(_plugIn, currMarker);
// tooltip will be shown via
} else {
// new places can always be edited
currMarker.showTooltip(true/*inRwMode*/);
}
});
gm.event.addListener(newMarker, "dragend", function (evt) {
var currMarker = this;
// only time when lat/lng can change!
currMarker.details.lat = evt.latLng.lat();
currMarker.details.lng = evt.latLng.lng();
var tip = $(currMarker.tooltip.content);
tip.find(".mapsed-lat").val(currMarker.details.lat);
tip.find(".mapsed-lng").val(currMarker.details.lng);
});
// for tooltip to be displayed
gm.event.trigger(newMarker, "click");
} // onPlaceAdd
/// <summary>
/// Internal event handler when the "Delete" button is clicked
/// - Builds the model and forwards onto the callback for confirmation.
/// </summary>
function onPlaceDelete(element) {
var $root = element.parents(".mapsed-root");
var $vw = $root.find(".mapsed-view");
var model = getViewModel($vw);
if (settings.onDelete(_plugIn, model)) {
// find the appropriate marker
var marker = findMarker(model.lat, model.lng);
// remove the marker
marker.setMap(null);
marker.tooltip = null;
}
} // onPlaceDelete
/// <summary>
/// Internal event handler when the "Save" button is clicked (in the edit dialog)
/// - Builds the model and forwards onto the callback for confirmation and validation
/// - Should the validation fail (callback returns error messages) the edit dialog
/// will remain for the user to resolve the errors
/// </summary>
function onPlaceSave(element) {
var root = element.parents(".mapsed-root");
var $rw = root.find(".mapsed-edit");
var errors = "";
var place = getViewModel($rw);
// see if the calling code is happy with what's being changed
errors = settings.onSave(_plugIn, place);
var errCtx = $rw.find(".mapsed-error");
if (errors && errors.length > 0) {
// not happy, show errors returned
errCtx.text(errors);
return;
}
// no errors
errCtx.text("");
// find the marker, so we can update the model on the marker
var marker = findMarker(place.lat, place.lng);
// update the model to reflect the changes made
jQuery.extend(marker.details, place);
// once an object has been edited successfully it becomes a normal editable "custom" object
root.find(".mapsed-marker-type").val("custom");
// also need to save back the userData (which may have changed, but is outside the view)
root.find(".mapsed-user-data").val(place.userData);
// editing complete, go back to the "Select" mode
marker.showTooltip(false/*inRwMode*/);
} // onPlaceSave
//
// GOOGLE EVENT HANDLERS
// - Set of Google events consumed by the plug-in
//
/// <summary>
/// Fires once the map has initially loaded. This lets us do some initialisation
/// for the map (e.g. change positions of buttons we've added to the map as these are
/// set by Google Maps so we have to wait until the map is loaded before we tweak them).
/// </summary>
function gmMapLoaded() {
// The line-height of the toolbar buttons seems to vary depending on the DIV size
// - we use this to flag what line-size the [Google] map controls are using
var gmToolBtns = $(_mapContainer.find(".gm-style-mtc"));
if (gmToolBtns.length > 0) {
var gmLineHeight = $(gmToolBtns[0]).css("line-height");
$(_mapContainer.find(".mapsed-control-button")).css("line-height", gmLineHeight);
}
if (_helpDlg) {
// note _helpBtn is the container, not the link inside the container
var btnContainer = _helpBtn;
// work out where the top-left of the dialog should be placed
var dialogLeft = btnContainer.position().left;
dialogLeft += (btnContainer.width() / 2);
dialogLeft -= (_helpDlg.width() / 2);
var dialogTop = btnContainer.position().top;
dialogTop += btnContainer.height() * 2;
_helpDlg
.css("z-index", 999)
.css("position", "absolute")
.css("top", dialogTop)
.css("right", "1%")
.css("width", "20%")
;
if (settings.showHelpOnLoad && _helpBtn.click) {
_helpBtn.trigger("click");
}
}
if (settings.findGeoOnLoad) {
_plugIn.setMapCentreByGeo();
}
} // gmMapLoaded
/// <summary>
/// Event hookup for when a place is selected by the end user from the search
/// control (if enabled).
/// places: Results from the Google Places API query
/// </summary>
function gmPlaceSelected(places, status, pagination) {
if (!_firstSearch) {
// If we're pre-populated the map with markers (via "showOnLoad" setting)
// and put some results up on start-up (via the "initSearch" option)
// we don't want to clear the markers as we'll remove the "showOnLoad"
// ones we've added
if (_pageNum == 0)
clearMarkers();
}
_firstSearch = false;
if (status == "ZERO_RESULTS") {
// nothing to see here
_plugIn.showMsg("No results", "Your search returned no results.");
}
// For each place, get the icon, place name, and location.
var bounds = new gm.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
if (!place.reference)
continue;
var pos = place.geometry.location;
var marker = addMarker(place, pos, "google", bounds);
// start off with just the minimal info we're given
// ... later we'll try and get more details, but if we can't at least
// ... we have _something_!
normaliseFormattedAddress(marker.details, place.formatted_address);
// expand the map out so the new places fit
bounds.extend(pos);
_gMap.fitBounds(bounds);
} // for
if (pagination) {
_moreBtn[0].disabled = !pagination.hasNextPage;
if (pagination.hasNextPage) {
gm.event.addDomListenerOnce(_moreBtn[0], "click", function () {
event.preventDefault();
_pageNum++;
pagination.nextPage();
});
}
}
} // gmPlaceSelected
/// <summary>
/// Helper method to perform a search to the Google Places API, translate
/// the results into something more useful for us and fire a callback once complete
/// </summary>
function getPlaceDetails(forMarker, callback) {
if (!forMarker.details)
return;
if (!forMarker.details.reference)
return;
var request = {
reference: forMarker.details.reference
};
_placesApi.getDetails(request,
function (placeDetails, status) {
// Either way we're loaded.
// If we fail, we revert to using the basic data (otherwise we'll just keep trying!)
forMarker.details.isLoaded = true;
if (status != gp.PlacesServiceStatus.OK) {
return;
}
normalisePlacesApiAddress(forMarker.details, placeDetails);
callback(forMarker);
}
);
} // getPlaceDetails
/// <summary>
/// Map boundary change event (moving map, zooming in or out, etc).
/// - Required so we can tell the search box (if enabled) that the
/// boundary of the map (and therefore the boundary the search should
/// be applied to) has changed.
/// </summary>
function gmBoundsChanged() {
var bounds = _gMap.getBounds();
if (bounds) {
_gmSearchBox.setBounds(bounds);
}
// Boundary has been set, so don't set the zoom/center
_areBoundsSet = true;
} // gmBoundsChanged
//
//
// PRIVATE METHODS
//
//
/// <summary>
/// Helper for building up a modal message on the screen.
/// title - text for the title bar
/// msg - message text to appear
/// doConfirm - internal flag tell us whether we're building an "alert" or a "confirm"
/// prompt - text to appear next to the action buttons
/// callback - callback for when Yes/OK is clicked.
/// Note the callback is _NOT_ called if "cancel" is pressed.
/// </summary>
function buildMsg(title, msg, doConfirm, prompt, callback) {
var $modal = null,
html = "",
buttons = ""
;
// protect from undefined
title = title || "";
msg = msg || "";
$modal = _mapContainer.find(".mapsed-modal");
if ($modal.length > 0) {
// usually we'd just re-use it, but we need to change basically
// everything (include the callback)
$modal.remove();
}
buttons += "<div class='mapsed-modal-button-bar'>";
if (prompt && prompt.length > 0) {
buttons += "<p class='prompt'>" + prompt + "</p>";
}
buttons += "<div class='mapsed-modal-buttons'>";
if (doConfirm) {
buttons += "<button class='ok'>OK</button>";
buttons += "<button class='cancel'>Cancel</button>";
} else {
buttons += "<button class='close'>OK</button>";
}
buttons += "</div>";
buttons += "</div>";
html =
"<div class='mapsed-modal'>" +
"<h3>" + title + "</h3>" +
"<div>" +
"<div class='mapsed-modal-message'>" +
msg +
"</div>" +
buttons +
"</div>" +
"</div>"
;
$modal = $(html).appendTo(_mapContainer);
$modal
.find("button")
.on("click", function () {
var $btn = $(this);
$modal.fadeOut();
if (!$btn.hasClass("cancel")) {
// only call the callback if we haven't cancelled
if (callback)
callback($btn);
}
})
.end()
.fadeIn()
;
} // showMsg
/// <summary>
/// Convenience function to add a new marker onto a map
/// and wire up the events (click, etc).
/// </summary>
function addMarker(model, position, markerType, inBoundary) {
var marker = createMarker(
model.name,
position,
false/*draggable*/,
markerType
);
jQuery.extend(marker.details, model);
attachTooltip(marker);
_markers.push(marker);
inBoundary.extend(position);
// wire up click event
gm.event.addListener(marker, "click", function () {
var m = this;
closeTooltips();
m.showTooltip(false/*inRwMode*/);
});
if (model.autoShow) {
// show on load enabled for marker
marker.showTooltip(false/*inRwMode*/);
}
_areBoundsSet = true;
return marker;
} // addMarker
/// <summary>
/// Convenience function to shorten a string to a
/// maximum length, adding an ellipsis (...) if required.
/// </summary>
function shorten(value, maxLen) {
var shortValue = value;
if (!maxLen) {
maxLen = 30;
}
if (value.length > maxLen) {
shortValue = value.substring(0, maxLen - 3) + "...";
}
return shortValue;
} // shorten
/// <summary>
/// Quick and dirty replace method for applying templates
/// </summary>
var replaceAll = function (find, replace, str) {
if (replace == undefined)
replace = "";
return str.replace(new RegExp(find, 'g'), replace);
} // replaceAll
/// <summary>
/// Quick and dirty template function, just does a replacement
/// according to our model ... nothing more advanced than that!
/// </summary>
function applyTemplate(tmpl, model, $ctx) {
tmpl = replaceAll("{NAME}", model.name, tmpl);
tmpl = replaceAll("{SHORT_NAME}", shorten(model.name, 25), tmpl);
tmpl = replaceAll("{STREET}", model.street, tmpl);
tmpl = replaceAll("{TOWN}", model.town, tmpl);
tmpl = replaceAll("{AREA}", model.area, tmpl);
tmpl = replaceAll("{POSTCODE}", model.postCode, tmpl);
tmpl = replaceAll("{TELNO}", model.telNo, tmpl);
tmpl = replaceAll("{WEBSITE}", model.website, tmpl);
tmpl = replaceAll("{GPLUS}", model.url, tmpl);
if (model.photo) {
var path = model.photo.getUrl({ "maxWidth": "70" });
tmpl = replaceAll("{PHOTOURL}", path, tmpl);
// used to delay when jQuery tries to render the image tag
tmpl = replaceAll("{IMG", "<img", tmpl);
}
if (model.addInfo) {
tmpl = replaceAll("{ADD_INFO}", model.addInfo, tmpl);
}
$ctx.html(tmpl);
} // applyTemplate
/// <summary>
/// Ensures when the view is shown any entities with nothing in them aren't
/// shown (and any that are shown, are shown correctly)
/// </summary>
function hideEmpty(model, $vw) {
// and hide bits that aren't relevant (or empty)
$vw.find(".mapsed-name").parent().toggle(model.name && model.name.length > 0);
$vw.find(".mapsed-street").toggle(model.street && model.street.length > 0);
$vw.find(".mapsed-town").toggle(model.town && model.town.length > 0);
$vw.find(".mapsed-area").toggle(model.area && model.area.length > 0);
$vw.find(".mapsed-postCode").toggle(model.postCode && model.postCode.length > 0);
// these are a little different as we want them block if they're available (they're a tags)
var $telNo = $vw.find(".mapsed-telNo"),
$ws = $vw.find(".mapsed-website"),
$url = $vw.find(".mapsed-url")
;
if (model.telNo && model.telNo.length > 0) {
$telNo.show().css("display", "block");
} else {
$telNo.hide();
}
if (model.website && model.website.length > 0) {
$ws.show().css("display", "block");
} else {
$ws.hide();
}
if (model.url && model.url.length > 0) {
$url.show().css("display", "block");
} else {
$url.hide();
}
$vw.find(".mapsed-photo").toggle(model.photo != null);
$vw.find(".mapsed-add-info").toggle(model.addInfo != null);
var settings = _plugIn.getSettings();
if (settings.onSelect || settings.onSave || settings.onDelete) {
var showSelect, showSave, showDelete, canEdit;
canEdit = model.canEdit;
// however if it's a google marker we can't, so ignore what the input says!
if (model.markerType == "google")
canEdit = false;
showSelect = settings.onSelect != null;
showSave = (settings.onSave != null && canEdit);
showDelete = (
settings.onDelete != null && canEdit
// can only delete markers we created!
&& model.markerType == "custom"
)
;
$vw.find(".mapsed-select-button").toggle(showSelect);
$vw.find(".mapsed-edit-button").toggle(showSave);
$vw.find(".mapsed-delete-button").toggle(showDelete);
} else {
// neither should be shown, so hide the button container to hide the whole row
$vw.find(".mapsed-buttons").hide();
}
} // hideEmpty
/// <summary>
/// Finds a marker in the loaded set based on the provided lat/lng
/// co-ordinates
/// - the model doesn't have a reference to the markers, hence the need to find them
/// </summary>
function findMarker(lat, lng) {
var marker = null;
for (var i = 0; i < _markers.length; i++) {
var m = _markers[i];
if (m.position.lat() == lat && m.position.lng() == lng) {
marker = m;
break;
}
}
return marker;
} // findMarker
/// <summary>
/// Adds a search box to the top left of the map which the user can use
/// to search for places of interest.
///
/// Google Maps API:
/// https://developers.google.com/maps/documentation/javascript/examples/places-searchbox
/// </summary>
function addSearch() {
var id = "mapsed-search-box-" + _instance;
_searchBox = $("#" + id);
if (_searchBox.length > 0)
// already added
return;
// create the "search" box and add to document (in body)
var so = settings.searchOptions,
html = "<input type='text' id='" + id + "' class='mapsed-searchbox' autocomplete='off' "
;
html += "placeholder='";
if (so.enabled && so.placeholder)
html += so.placeholder;
else
html += "Search ...";
html += "' ";
if (so.enabled && so.initSearch && so.initSearch.length > 0)
html += " value='" + so.initSearch + "'";
html += " />";
_searchBox = $(html).appendTo(_mapContainer);
// associate with places api
// ... note Google Maps API doesn't play well with jQuery
_gmSearchBox = new gp.SearchBox(_searchBox[0]);
// Place search box onto the screen
_gMap.controls[gm.ControlPosition.TOP_LEFT].push(_searchBox[0]);
// and wire up the callback when a user selects a hit
gm.event.addListener(_gmSearchBox, "places_changed",
function () {
var searchFor = _searchBox.val();
doSearch(searchFor);
}
);
// and again for when they zoom in/out
gm.event.addListener(_gMap, "bounds_changed", gmBoundsChanged);
_searchBtn = createControlButton(
settings.ToolbarButtons.Go, gm.ControlPosition.TOP_LEFT,
"mapsed-search-button mapsed-control-button",
function (evt) {
evt.preventDefault();
var searchFor = _searchBox.val();
doSearch(searchFor);
}
);
// For handling additional results, note there is not event handlers as this is]
// ... driven from the first set of search results we get back from Google
_moreBtn = createControlButton(