What is the standard way in gmaps4rails for dynamically resetting marker icons / pictures? - gmaps4rails

All I want to do is dynamically reset a marker's icon. For example, suppose a red marker is pinned to a specific location on the map. A user-interaction occurs which requires the red marker to become yellow. In this case, I would expect to be able to do something like this:
var icon = marker.serviceObject.getIcon();
if ($("#chooseJobsForWorkSite ul li input:checked").size() > 0) {
icon.url = "/assets/purple_MarkerT.png";
} else {
icon.url = "/assets/green_MarkerS.png";
}
marker.serviceObject.setIcon(icon);
This works fine for a single marker, but when I loop across this code for more than
one marker, something goes wrong -- I do not get the desired colors for all markers.

I resolved this issue by using the replaceMarkers API method. Here's the code that worked:
var replacementMarkers = new Array();
for (var k = 0; k < activeMarkers.length; ++k) {
var marker = activeMarkers[k];
var iconUrl = null;
if ($.inArray(marker, taskMarkers) >= 0) {
iconUrl = "/assets/purple_MarkerT.png";
} else {
iconUrl = "/assets/green_MarkerS.png";
}
replacementMarkers.push({
"lat": marker.lat.toString(),
"lng": marker.lng.toString(),
"picture": iconUrl,
"id": marker.id,
"description": marker.description
});
}
// Delay the replacement operation because in some instances, we reach this branch via the Gmaps.map.callback.
// In that case, I prefer to defer touching the gmap4rails until the current branch is done.
window.setTimeout(function() {
Gmaps.map.replaceMarkers(replacementMarkers);
resetAddressMarkers();
}, 25);

Related

Items alignment in the PopupMenuBarItem

I'm absolutely newbie in the Dojo, so my question may be too evident. Sorry.
I've programmatically created the complex menu, including MenuBar, based on the rows, selected from the DB.
All problems were solved besides one: the alignment of the final items and submenu items differ.How it looks like All submenus primarily were rendered in the same line. Only by adding the MenuSeparator I was able to divide them.
I'm lost I've found the example in the Internet, that shows exactly what I need (including the right-hand arrow for submenus) Example . I've used exactly the same algorithm to create menu. But I cannot get the same result.
Please, help.
I've noted that the image is not accessible.
In pure text it looks like:
Final 1
Final 2
Final 3
DropDown 1
DropDown 2
Indent depends on the submenu width.
Think, now I know what happened (don't know though, how to work around it).
The problem is the widget rendering.
The final menu option (leaf) is rendered as table row (tr and td tags).
The PopupMenuItem is rendered as div between rows.
Once more, I have no clue, how to avoid it.
Here is the code. A couple of notes:
1.The rows is the two dimensional array
2.The rows with ParentID=0 are the MenuBarItems
3.pM is the MenuBar widget
createMenu: function (rows, pM) {
var me = this; // for references from the event handlers, where 'this' means event origin (instead of lang.hitch)
// First define the indexes of the DB fields
var xMenu_Id;
var xMenu_Title;
var xParent;
var xURL;
var xUser_Roles;
var i;
for (i = 0; i < rows[0].length; i++) {
switch (rows[0][i]) {
case 'Menu_Id':
xMenu_Id = i;
break;
case 'Menu_Title':
xMenu_Title = i;
break;
case 'Parent':
xParent = i;
break;
case 'URL':
xURL = i;
break;
case 'User_Roles':
xUser_Roles = i;
break;
}
}
// Define the function to filter the menu rows
// Parameters: r - two-dimentional rows array
// p - criterion (the parent menu ID)
// idx - index of needed field
// f - returned filtered array (no need to use in calling statement)
var filterArray = function (r, p, idx, f) {
f = dojo.filter(r, function (item) {
return item[idx] == p;
});
return f;
}
// Define the recurcive function to create the sub menu tree for Menu bar item
// Parameters: parentMenu - the menu to add childs
// parentID - the ID of parent menu to select direct children
// role - current user role
var subMenuFactory = function (parentMenu, parentID, role) {
var i;
var fa = filterArray(rows, parentID, xParent);
var sub;
for (i = 0; i < fa.length; i++) {
if (fa[i][xUser_Roles].indexOf(role) >= 0 || fa[i][xUser_Roles] == 'all') {
if (fa[i][xURL] != '0') { // leaf
url = fa[i][xURL];
parentMenu.addChild(new MenuItem({
dir: 'ltr',
label: fa[i][xMenu_Title],
action: fa[i][xURL],
onClick: function () { me.menuAction(this.action); }
}));
}
else { // DropDown Node
sub = new DropDownMenu({ dir: 'ltr' });
subMenuFactory(sub, fa[i][xMenu_Id], role);
parentMenu.addChild(new MenuSeparator({}));
parentMenu.addChild(new PopupMenuBarItem({
dir: 'ltr',
label: fa[i][xMenu_Title],
popup: sub
}));
}
}
}
}
// Get array of Menu bar items
var filtered = filterArray(rows, 0, xParent);
var pSub;
var user_Role = this.user.Role;
for (i = 0; i < filtered.length; i++) {
if (filtered[i][xUser_Roles].indexOf(user_Role) >= 0 || filtered[i][xUser_Roles]=='all') {
if (filtered[i][xURL] != '0') // leaf
{
pM.addChild(new MenuBarItem({
dir: 'ltr',
label: filtered[i][xMenu_Title],
action: filtered[i][xURL],
onClick: function () { me.menuAction(this.action); }
}));
}
else { // DropDown Node
pSub = new DropDownMenu({ dir: 'ltr' });
subMenuFactory(pSub, filtered[i][xMenu_Id],user_Role);
pM.addChild(new PopupMenuBarItem({
dir: 'ltr',
label: filtered[i][xMenu_Title],
popup: pSub
}));
}
}
}
},
I've found what's the problem. In the required array of define I erroneously import PopupMenubarItem instead of PopupMenuItem. In the function the parameter is named right - PopupMenuItem, but evidently it couldn't help a lot...
Thanks to everyone who tried to help me.
Regards,
Gena

Google Maps API - Map not showing on second initialize

I have a page setup that requires multiple instances of Google Maps via the API to be initialized. All works fine when one map is initialized the first time. When you re click on the button to do so, the map does not fully show.
var locations = [
['test1', 45.440188, -75.676309, 1, 'transportation.png'],
['test2', 45.439463, -75.675751, 1, 'medical.png'],
['test3', 45.439792, -75.683544, 1, 'schools.png'],
['test4', 45.439652, -75.676929, 1, 'shopping.png']
];
function initialize_1() {
var mapOptions = {
center: new google.maps.LatLng(45.438612, -75.677561),
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas_1"), mapOptions);
marker = new google.maps.Marker({
position: new google.maps.LatLng(45.438612, -75.677561),
map: map
});
var marker, i;
var iconBase = 'http://www.elkproperty.com/new/images/icons/';
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
,icon: iconBase + locations[i][4]
});
}
}
I think the issue is that you are initialising map to a hidden layer. Try to move call to initialize_1() after show():
onclick="$('#units_1').hide(); $('#unitArrow_1').hide(); $('#amenity_1').show(); $('#amenityArrow_1').show(); initialize_1();"
Other option is to force resize event after divs are visible. For this to work you would probably have to make map variable global.
google.maps.event.trigger(map, 'resize');
Maybe unrelated to your question but do you have to initialise the map layer each time you show div with map? Maybe you could test whether it is initialised or not, for example:
var isInit_1 = false;
function initialize_1() {
if (isInit_1) { return; }
isInit_1 = true;
var mapOptions = {
...

Triggering clearIconTap callback on dynamically created fields

I am creating a simple app using Sencha Touch where I'm dynamically creating container with textfields, textareafields etc. when the user needs to add new container with components. The problem now is when the clear icon on the textareafield is tapped it clears the text, but I would like to know which textareafield has been cleared. Can anyone help me in this please?
This is how I created container .
var childObj2 = {};
childObj2.xtype = 'container';
var type = 'vbox';
var layout = {}
layout.type = type;
childObj1.layout = layout;
var txtarea= {};
txtarea.xtype = 'textareafield';
txtarea.id = "txt51";
txtarea.flex = 3;
txtarea.maxRows = 7;
txtarea.placeHolder = 'Type here';
txtarea.value = value['notes'];
txtarea.inputCls = 'txtareaStyle'
txtarea.clearicontap = "clearText";
How to add clearicontap listener to this?
When you you create a textfield simply add a listener to it for the clearicontap event and that callback will get executed for each of the fields.
For example:
var container = Ext.create('Ext.Container', {});
for (var i=1; i<=3; i++) {
var field = Ext.create('Ext.field.Text', {
id: 'textfieldnumber' + i,
listeners: {
clearicontap: function() {
alert("Tapped clear icon on text field number: " + i + "!");
}
}
});
container.add(field);
}
[EDIT]
I answer the question you make after your edit:
I am using the standard way of creating Sencha components through Ext.create(), and I would suggest you to switch to the same way. It is not clear by the code you posted how those Javascript objects are actually transformed into Ext components. Anyway, they are very likely components configurations, so I guess you could try:
txtarea.listeners = {
clearicontap: function() {
alert("Tapped clear icon on text field");
}
}

Cannot dynamically change a caption 'track' in Video.js

I'm coding a basic video marquee and one of the key requirements is that the videos need to be able to advance while keeping the player in full screen.
Using Video.js (4.1.0) I have been able to get everything work correctly except that I cannot get the captions to change when switching to another video.
Either inserting a "track" tag when the player HTML is first created or adding a track to the 'options' object when the player is initialized are the only ways I can get the player to display the "CC" button and show captions. However, I cannot re-initialize the player while in full screen so changing the track that way will not work.
I have tried addTextTrack and addTextTracks and both show that the tracks have been added - using something like console.log(videoObject.textTracks()) - but the player never shows them or the "CC" button.
Here is my code, any help is greatly appreciated:
;(function(window,undefined) {
// VIDEOS OBJECT
var videos = [
{"volume":"70","title":"TEST 1","url":"test1.mp4","type":"mp4"},
{"volume":"80","title":"TEST 2","url":"test2.mp4","type":"mp4"},
{"volume":"90","title":"TEST 3","url":"test3.mp4","type":"mp4"}
];
// CONSTANTS
var VIDEO_BOX_ID = "jbunow_marquee_video_box", NAV_TEXT_ID = "jbunow_marquee_nav_text", NAV_ARROWS_ID = "jbunow_marquee_nav_arrows", VIDEO_OBJ_ID = "jbunow_marquee_video", NAV_PREV_ID = "jbunow_nav_prev", NAV_NEXT_ID = "jbunow_nav_next";
// GLOBAL VARIABLS
var videoObject;
var currentTrack = 0;
var videoObjectCreated = false;
var controlBarHideTimeout;
jQuery(document).ready(function(){
// CREATE NAV ARROWS AND LISTENERS, THEN START MARQUEE
var navArrowsHtml = "<div id='" + NAV_PREV_ID + "' title='Play Previous Video'></div>";
navArrowsHtml += "<div id='" + NAV_NEXT_ID + "' title='Play Next Video'></div>";
jQuery('#' + NAV_ARROWS_ID).html(navArrowsHtml);
jQuery('#' + NAV_PREV_ID).on('click',function() { ChangeVideo(GetPrevVideo()); });
jQuery('#' + NAV_NEXT_ID).on('click',function() { ChangeVideo(GetNextVideo()); });
ChangeVideo(currentTrack);
});
var ChangeVideo = function(newIndex) {
var videoBox = jQuery('#' + VIDEO_BOX_ID);
if (!videoObjectCreated) {
// LOAD PLAYER HTML
videoBox.html(GetPlayerHtml());
// INITIALIZE VIDEO-JS
videojs(VIDEO_OBJ_ID, {}, function(){
videoObject = this;
// LISTENERS
videoObject.on("ended", function() { ChangeVideo(GetNextVideo()); });
videoObject.on("loadeddata", function () { videoObject.play(); });
videoObjectCreated = true;
PlayVideo(newIndex);
});
} else { PlayVideo(newIndex); }
}
var PlayVideo = function(newIndex) {
// TRY ADDING MULTIPLE TRACKS
videoObject.addTextTracks([{ kind: 'captions', label: 'English2', language: 'en', srclang: 'en', src: 'track2.vtt' }]);
// TRY ADDING HTML
//jQuery('#' + VIDEO_OBJ_ID + ' video').eq(0).append("<track kind='captions' src='track2.vtt' srclang='en' label='English' default />");
// TRY ADDING SINGLE TRACK THEN SHOWING USING RETURNED ID
//var newTrack = videoObject.addTextTrack('captions', 'English2', 'en', { kind: 'captions', label: 'English2', language: 'en', srclang: 'en', src: 'track2.vtt' });
//videoObject.showTextTrack(newTrack.id_, newTrack.kind_);
videoObject.volume(parseFloat(videos[newIndex]["volume"]) / 100); // SET START VOLUME
videoObject.src({ type: "video/" + videos[newIndex]["type"], src: videos[newIndex]["url"] }); // SET NEW SRC
videoObject.load();
videoObject.ready(function () {
videoObject.play();
clearTimeout(controlBarHideTimeout);
controlBarHideTimeout = setTimeout(function() { videoObject.controlBar.fadeOut(); }, 2000);
jQuery('#' + NAV_TEXT_ID).fadeOut(150, function() {
currentTrack = newIndex;
var navHtml = "";
navHtml += "<h1>Now Playing</h1><h2>" + videos[newIndex]["title"] + "</h2>";
if (videos.length > 1) { navHtml += "<h1>Up Next</h1><h2>" + videos[GetNextVideo()]["title"] + "</h2>"; }
jQuery('#' + NAV_TEXT_ID).html(navHtml).fadeIn(250);
});
});
}
var GetPlayerHtml = function() {
var playerHtml = "";
playerHtml += "<video id='" + VIDEO_OBJ_ID + "' class='video-js vjs-default-skin' controls='controls' preload='auto' width='560' height='315'>";
playerHtml += "<source src='' type='video/mp4' />";
//playerHtml += "<track kind='captions' src='track.vtt' srclang='en' label='English' default='default' />";
playerHtml += "</video>";
return playerHtml;
}
var GetNextVideo = function() {
if (currentTrack >= videos.length - 1) { return 0; }
else { return (currentTrack + 1); }
}
var GetPrevVideo = function() {
if (currentTrack <= 0) { return videos.length - 1; }
else { return (currentTrack - 1); }
}
})(window);
The current VideoJS implementation (4.4.2) loads every kind of text tracks (subtitles, captions, chapters) on initialization time of the player itself, so it grabs correctly only those, which are defined between the <video> tags.
EDIT: I meant it does load them when calling addTextTrack, but the player UI will never update after initialization time, and will always show the initialization time text tracks.
One possible workaround is if you destroy the complete videojs player and re-create it on video source change after you have refreshed the content between the <video> tags. So this way you don't update the source via the videojs player, but via dynamically adding the required DOM elements and initializing a new player on them. Probably this solution will cause some UI flashes, and is quite non-optimal for the problem. Here is a link about destroying the videojs player
Second option is to add the dynamic text track handling to the existing code, which is not as hard as it sounds if one knows where to look (I did it for only chapters, but could be similar for other text tracks as well). The code below works with the latest official build 4.4.2. Note that I'm using jQuery for removing the text track elements, so if anyone applies these changes as is, jQuery needs to be loaded before videojs.
Edit the video.dev.js file as follows:
1: Add a clearTextTracks function to the Player
vjs.Player.prototype.clearTextTracks = function() {
var tracks = this.textTracks_ = this.textTracks_ || [];
for (var i = 0; i != tracks.length; ++i)
$(tracks[i].el()).remove();
tracks.splice(0, tracks.length);
this.trigger("textTracksChanged");
};
2: Add the new 'textTracksChanged' event trigger to the end of the existing addTextTrack method
vjs.Player.prototype.addTextTrack = function(kind, label, language, options) {
...
this.trigger("textTracksChanged");
}
3: Handle the new event in the TextTrackButton constructor function
vjs.TextTrackButton = vjs.MenuButton.extend({
/** #constructor */
init: function(player, options) {
vjs.MenuButton.call(this, player, options);
if (this.items.length <= 1) {
this.hide();
}
player.on('textTracksChanged', vjs.bind(this, this.refresh));
}
});
4: Implement the refresh method on the TextTrackButton
// removes and recreates the texttrack menu
vjs.TextTrackButton.prototype.refresh = function () {
this.removeChild(this.menu);
this.menu = this.createMenu();
this.addChild(this.menu);
if (this.items && this.items.length <= this.kind_ == "chapters" ? 0 : 1) {
this.hide();
} else
this.show();
};
Sorry, but for now I cannot link to a real working example, I hope the snippets above will be enough as a starting point to anyone intrested in this.
You can use this code when you update the source to a new video. Just call the clearTextTracks method, and add the new text tracks with the addTextTrack method, and the menus now should update themselves.
Doing the exact same thing (or rather NOT doing the exact same thing)... really need to figure out how to dynamically change / add a caption track.
This works to get it playing via the underlying HTML5, but it does not show the videojs CC button:
document.getElementById("HtmlFiveMediaPlayer_html5_api").innerHTML = '<track label="English Captions" srclang="en" kind="captions" src="http://localhost/media/captiontest/demo_Brian/demo_h264_1.vtt" type="text/vtt" default />';

Titanium Infinite Scroll : Not working

I am trying to add views to my scroll view when it reaches 40% scroll. This is the way I am doing it :
scrollView.add(//add first 10 initial containerView's);
var triggerScroll = true;
var scrollPercentage = 0;
scrollView.addEventListener('scroll', function(e) {
var devHeight = Ti.Platform.displayCaps.platformHeight;
var currPos = scrollView.contentOffset.y;
if(currPos > devHeight){
currPos = currPos - devHeight;
}
scrollPercentage = (currPos)/devHeight * 100;
if(scrollPercentage > 40 && triggerScroll){
triggerScroll = false;
var containerView = myapp.createMyView();
scrollView.add(containerView);
}
//reset scroll to true after the offset reaches end of the screen, so that the
//'scroll' event listener only gets called ONCE every time it crosses 40%
if(scrollPercentage > 101){
triggerScroll = true;
}
});
But its just not working. I am trying to support infinite scroll in my vertical scroll view. Any idea whats going wrong ?
I use the module below when working with infinite scrolling. It use a TableView, but I would think you can apply it to a ScrollView as well. You need to pass in a function that will be called when the TableView register that more content should be loaded.
When you have finished loading you must call the loadingDone-function in order to enable the TableView to initiate another loading sequence.
The value m_bNoDataFound ensure that the loading sequence is not initiated, when there is no more data to fill into the list.
You can alter the offsets (currently 0.75 for Android and 0.90 for iOS) if want the loading sequence to be initiated sooner or later during scroll.
function TableView( onLoad ) {
var isAndroid = Ti.Platform.osname === 'android' ? true : false;
var m_bNoDataFound = false;
var m_nLastDistance = 0;
var m_bPulling = false;
var m_bLoading = false;
var table = Ti.UI.createTableView( {
height : Ti.UI.FILL
} );
table.addEventListener( 'scroll', function( evt ) {
//Scroll to load more data
if( !m_bNoDataFound ) {
if( isAndroid ) {
if( !m_bLoading && ( evt.firstVisibleItem + evt.visibleItemCount ) >= ( evt.totalItemCount * 0.75 ) ) {
onLoad( true );
m_bLoading = true;
}
}
else {
var nTotal = evt.contentOffset.y + evt.size.height;
var nEnd = evt.contentSize.height;
var nDistance = nEnd - nTotal;
if( nDistance < m_nLastDistance ) {
var nNearEnd = nEnd * 0.90;
if( !m_bLoading && ( nTotal >= nNearEnd ) ) {
onLoad( true );
m_bLoading = true;
}
}
m_nLastDistance = nDistance;
}
}
} );
function m_fLoadingDone( a_bNoDataFound ) {
m_bNoDataFound = a_bNoDataFound;
if( m_bLoading )
setTimeout( function( ) {
m_bLoading = false;
}, 250 );
}
return {
table : table,
loadingDone : m_fLoadingDone
};
};
module.exports = TableView;
When integrating an infinite scroll within a scrollview, there are some important things you have to consider:
1. scroll event is triggered a lot: try to throttle your scroll event callback using underscoreJS.
Throttle creates and returns a new, throttled version of the passed function, that, when invoked repeatedly, will only actually call the original function at most once per every wait milliseconds. Useful for rate-limiting events that occur faster than you can keep up with. See the underscorejs documentation for more.
2. Default and system units on Android vs iOS: The size of a view on Android uses a different display unit than coordinates of a view. This mismatch in units will cause incorrect calculation of your trigger for the infinite scroll. To solve this, you have to get and set the default unit yourself. The solution can be found in this widget (see getDefaultUnit()): https://github.com/FokkeZB/nl.fokkezb.color/blob/master/controllers/widget.js
3. The ti-infini-scroll can help you with this: this library creates a wrapper around the default Titanium ScrollView. This wrapper contains the calculation of the end of scroll (your trigger for updating/getting new data). When using this library, don't forget to implement bullet number 2.
https://github.com/goodybag/ti-infini-scroll