Leaflet-routing-machine: Is there a way to load waypoints if they have been saved in some kind of data store? - leaflet

I followed this great tutorial, add because of it was able to add it to my routing machine; However, I'd like to save the waypoints in local-storage and load them when needed.
I tried this when creating my Routing Machine:
if (map && !this.control) {
this.control = L.Routing.control({
collapsible: true,
show: false,
position: 'bottomleft',
lineOptions: {
styles: [{ color: 'chartreuse', opacity: 1, weight: 5 }]
},
waypoints: [null], //<--- I set the waypoints to null
createMarker: function(i, wp, nWps) {
if (i === 0) {
return L.marker(wp.latLng, {
icon: startIcon,
draggable: true
});
}
if (i === nWps - 1) {
return L.marker(wp.latLng, {
icon: endIcon,
draggable: true
});
}
}
})
.on('routingstart', this.handleLoader.bind(this))
.on('routeselected', function(e) {
var route = e.route;
})
.on('routesfound routingerror', this.handleLoader.bind(this));
And then in the initial listeners for the click events for the start and destination events:
map.on(
'click',
function(e) {
var container = L.DomUtil.create('div'),
startBtn = createButton('Start from this location', container),
destBtn = createButton('Go to this location', container);
function createMarkerHelper(marker) {
setUserMarkers(marker);
}
L.popup()
.setContent(container)
.setLatLng(e.latlng)
.openOn(map);
L.DomEvent.on(
startBtn,
'click',
function() {
var wayPointStart = this.control.getWaypoints()[0].latLng;
if (wayPointStart != null && userMarkers[0] !== undefined) {
this.control.spliceWaypoints(0, 1, userMarkers[0]);
} else {
this.control.spliceWaypoints(0, 1, e.latlng);
createMarkerHelper(e.latlng);
}
map.closePopup();
}.bind(this)
);
L.DomEvent.on(
destBtn,
'click',
function() {
var wapPointDestination = this.control.getWaypoints()[1].latLng;
if (wapPointDestination != null && userMarkers[1] !== undefined) {
this.control.spliceWaypoints(
this.control.getWaypoints().length - 1,
1,
userMarkers[1]
);
} else {
this.control.spliceWaypoints(
this.control.getWaypoints().length - 1,
1,
e.latlng
);
createMarkerHelper(e.latlng);
}
map.closePopup();
}.bind(this)
);
}.bind(this)
);
So this is what I tried for when one starting click event:
function() {
var wayPointStart = this.control.getWaypoints()[0].latLng;
if (wayPointStart != null && userMarkers[0] !== undefined) {
this.control.spliceWaypoints(0, 1, userMarkers[0]);
} else {
this.control.spliceWaypoints(0, 1, e.latlng);
createMarkerHelper(e.latlng);
}
map.closePopup();
}.bind(this)
So essentially I am using the getWaypoints method to check if the waypoint is null, (it would be during a fresh start) and checking if any Markers are in local storage if that conditional is true it would naturally load the markers. If not true it would just set it like normal.
Then later Leaflet has a update function, which you can use to see if props change:
updateLeafletElement(fromProps, toProps) {
var start =
toProps.userMarkers[0] !== undefined &&
this.control.getWaypoints()[1].latLng != null
? toProps.userMarkers[0]
: null,
destination =
toProps.userMarkers[1] !== undefined &&
this.control.getWaypoints()[1].latLng != null
? toProps.userMarkers[1]
: null;
this.control.spliceWaypoints(0, 1, start);
this.control.spliceWaypoints(this.control.getWaypoints().length - 1, 1, destination);
if (toProps.removeRoutingMachine !== false) {
this.control.setWaypoints([]);
}
}
My thinking is this would always ensure the markers are always being updated. But it hasn't worked.
Any ideas? Thanks in advance!

Related

Fire BarcodeScannerButton after View loads

I have implemented a scanner button on my Fiori/UI5 application. I used sap.ndc.BarcodeScannerButton and created that button on the controller (I cannot seem to create the button on my view.xml).
Anyway, I need to fire this button after the view loads. I have a master-detail application. The scanner button is on the master view ofcourse.
First thing I did was call the button itself. But my first problem is that the button does not accept an id as a parameter. It tells me that app cannot accept duplicate id. So what I did was just look for the button id. I was able to locate it (e.g. _button9) but whenever I call it via sap.ui.getCore.byId() there are times that it returns "undefined." That's why I cannot call firePress();
Another problem I have is where to put this firePress() method. I tried to put it on method onAfterRendering() assuming that again due to the undefined button I cannot call the method firePress(). I have tried putting it on other methods like after the data has been successfully called by using method attachRequestCompleted. No luck.
Below is the code
/*
* Copyright (C) 2009-2014 SAP SE or an SAP affiliate company. All rights reserved
*/
jQuery.sap.require("sap.ca.scfld.md.controller.ScfldMasterController");
jQuery.sap.require("ui.s2p.srm.sc.create.util.Formatter");
jQuery.sap.require("sap.ndc.BarcodeScannerButton");
var counter = 0;
sap.ui.controller("ui.s2p.srm.sc.create.SRM_SC_CREExtension.view.S2Custom", {
onInit: function() {
sap.ca.scfld.md.controller.ScfldMasterController.prototype.onInit.call(this);
this.oBundle = this.oApplicationFacade.getResourceBundle();
this.isRoot = true;
this.oRouter.attachRouteMatched(function(e) {
if (e.getParameter("name") === "master" && !this.isRoot && Object.keys(e.getParameter("arguments")).length === 0) {
var d = sap.ui.core.routing.History.getInstance().getDirection("shoppingCartCheckout/" + this.tempCartId);
if (d === "Unknown") {
this.isRoot = true;
this._oControlStore.oMasterSearchField.clear()
} else {
if (this.getList() !== null) {
var i = this.getList().getSelectedItem();
if (i !== null) {
//alert("setListGo");
this.setListItem(i);
}
}
}
}
this.isRoot = (this.isRoot) ? false : this.isRoot;
}, this);
// alert(sap.ui.getCore().byId("productScanButton"));
this.onBarcodeScanning();
this.setEmptyCart(true);
this.showAllProducts(); //added by salduam to show all products
},
backToList: function() {
//alert("back");
},
getDefaultUserSettings: function(r) {
var o = function(D, R) {
this.tempCartId = D.results[0].TEMP_CART_ID;
if (!jQuery.device.is.phone) {
if (r) {
this.oRouter.navTo("noData", {
viewTitle: "DETAIL_TITLE",
languageKey: "NO_ITEMS_AVAILABLE"
}, true)
} else {
this.navToEmptyView()
}
}
};
var d = this.oApplicationFacade.getODataModel("getdefusrset");
d.read("DefaultUserSettings?ts=" + Date.now(), null, null, true, jQuery.proxy(o, this), jQuery.proxy(this.onRequestFailed, this))
},
applySearchPatternToListItem: function(i, f) {
if (f.substring(0, 1) === "#") {
var t = f.substr(1);
var d = i.getBindingContext().getProperty("Name").toLowerCase();
return d.indexOf(t) === 0
} else {
return sap.ca.scfld.md.controller.ScfldMasterController.prototype.applySearchPatternToListItem.call(null, i, f)
}
},
getHeaderFooterOptions: function() {
var o = {
sI18NMasterTitle: "MASTER_TITLE",
buttonList: []
};
return o
},
isBackendSearch: function() {
return true
},
//call startReadListData with parameter wildcard
showAllProducts: function(e) {
var startSearchText = "*";
this.startReadListData(startSearchText);
//alert("called");
},
applyBackendSearchPattern: function(f, b) {
//added by salduam
//if search field is blank, automatically call showAllProducts
if (f == "") {
this.showAllProducts()
};
if (f != "" && f != null) {
this.startReadListData(f)
} else {
this.setEmptyCart(false)
}
},
startReadListData: function(f) {
var o = function(D, r) {
var m = new sap.ui.model.json.JSONModel(D.results);
this.getView().setModel(m);
this.getList().destroyItems();
this.getList().bindAggregation("items", {
path: "/",
template: this.oTemplate.clone(),
filter: [],
sorter: null
});
this.registerMasterListBind(this.getList());
};
var e = encodeURIComponent(f);
//console.log("EEEE-----"+ e);
var d = this.oApplicationFacade.getODataModel();
//console.log(d);
d.read("CATALOG_ITEM?$filter=startswith(description,'" + e + "')&$top=20", null, null, true, jQuery.proxy(o, this), jQuery.proxy(this.onRequestFailed,
this));
},
setListItem: function(i) {
// alert("onClick");
var b = i.getBindingContext();
var m = b.oModel.oData[parseInt(b.sPath.split('/')[1])];
this.oRouter.navTo("detail", {
tempCartId: this.tempCartId,
contextPath: b.getPath().substr(1)
}, true);
var c = sap.ui.core.Component.getOwnerIdFor(this.oView);
var C = sap.ui.component(c);
C.oEventBus.publish("ui.s2p.srm.sc.create", "refreshDetail", {
data: m
});
},
setEmptyCart: function(r) {
var e = new sap.ui.model.json.JSONModel({
results: []
});
this.oRouter.navTo("noData", {
viewTitle: "DETAIL_TITLE",
languageKey: "NO_ITEMS_AVAILABLE"
}, true);
this.getView().setModel(e);
this.oTemplate = new sap.m.ObjectListItem({
type: "{device>/listItemType}",
title: "{matnr}",
press: jQuery.proxy(this._handleItemPress, this),
number: "{parts:[{path:'itm_price'},{path:'itm_currency'}],formatter:'ui.s2p.srm.sc.create.util.Formatter.formatPrice'}",
numberUnit: "{itm_currency}",
attributes: [new sap.m.ObjectAttribute({
text: "{description}"
})],
});
this.getList().bindAggregation("items", {
path: "/results",
template: this.oTemplate,
filter: [],
sorter: null,
});
this.registerMasterListBind(this.getList());
this.getDefaultUserSettings(r)
},
onRequestFailed: function(e) {
jQuery.sap.require("sap.ca.ui.message.message");
sap.ca.ui.message.showMessageBox({
type: sap.ca.ui.message.Type.ERROR,
message: e.message,
details: e.response.body
})
},
onExit: function() {},
onBarcodeScanning: function(oEvent) {
var productScanButton = new sap.ndc.BarcodeScannerButton({
provideFallback: "{/btnFallback}",
width: "100%",
scanSuccess: function(oEvent) {
var barcodeID = oEvent.getParameter("text");
sap.m.MessageToast.show(barcodeID);
var searchField = sap.ui.getCore().byId("__field3");
searchField.setValue(barcodeID);
searchField.fireSearch();
}
});
this.getView().byId("barCodeVBox").addItem(productScanButton);
},
onAfterRendering: function(oEvent) {},
onBeforeRendering: function() {}
});
For placing the fire() method. Are you trying to display a pop-up barcode reader? something similar to the pop-up of the app "SD_SO_CRE" (where customer selection dialog is load before master view).
they do not solve the task with fire()...

hash format error! using routing

I have developed an OpenUI5 app ant it works fine!
But every time that I invoke the routing I have this message:
2015-07-15 16:15:45 hash format error! The current Hash: /line/01 -
log
error
onHashChange
detectHashChange
jQuery.event.dispatch
jQuery.event.add.elemData.handle
It is not a blocking problem but it is annoying because it dirty and fills thi debug console..!
To call the router I write:
this.router = sap.ui.core.UIComponent.getRouterFor(this);
this.router.navTo("activities", {
"id_line": '01'
});
and this is the routing file:
routes: [
...
{
pattern: "line/{id_line}",
name: "activities",
target: ["master_search", "detail_activities"]
},
...
],
targets: {
master_search: {
viewName: "UniversalMenu",
viewLevel: 1,
controlAggregation: "masterPages"
}
,
detail_activities: {
viewName: "DetailActivity",
viewLevel: 4
}
...
}
Edit: this is a snippet where I use jQuery.sap.history
jQuery.sap.require("jquery.sap.history");
jQuery.sap.require("sap.m.InstanceManager");
sap.ui.controller("ui5bp.view.App", {
getDefaultPage : function () {
return "Menu";
},
onInit : function () {
var historyDefaultHandler = function (navType) {
if (navType === jQuery.sap.history.NavType.Back) {
//this.navBack(this.getDefaultPage());
} else {
this.navTo(this.getDefaultPage(), null, false);
}
};
var historyPageHandler = function (params, navType) {
if (!params || !params.id) {
jQuery.sap.log.error("invalid parameter: " + params);
} else {
if (navType === jQuery.sap.history.NavType.Back) {
this.navBack(params.id);
} else {
this.navTo(params.id, params.data, false);
}
}
};
jQuery.sap.history({
routes: [{
// This handler is executed when you navigate back to the history state on the path "page"
path : "page",
handler : jQuery.proxy(historyPageHandler, this)
}],
// The default handler is executed when you navigate back to the history state with an empty hash
defaultHandler: jQuery.proxy(historyDefaultHandler, this)
});
// subscribe to event bus
var bus = sap.ui.getCore().getEventBus();
bus.subscribe("nav", "to", this.navHandler, this);
bus.subscribe("nav", "back", this.navHandler, this);
bus.subscribe("nav", "virtual", this.navHandler, this);
},
navHandler: function (channelId, eventId, data) {
if (eventId === "to") {
this.navTo(data.id, data.data, true);
} else if (eventId === "back") {
//**************************************************
// if(data && data.id){
// this.navBack(data.id);
// } else {
// jQuery.sap.history.back();
// }
var app = this.getView().app;
if(data.type==="master"){
app.backMaster();
}else if(data.type==="detail"){
app.backDetail();
}else{alert("back to master o detail?");};
//**************************************************
} else if (eventId === "virtual") {
jQuery.sap.history.addVirtualHistory();
} else {
jQuery.sap.log.error("'nav' event cannot be processed. There's no handler registered for event with id: " + eventId);
}
},
navTo : function (id, data, writeHistory) {
if (id === undefined) {
// invalid parameter
jQuery.sap.log.error("navTo failed due to missing id");
} else {
var app = this.getView().app;
// navigate in the app control
app.to(id, "slide", data);
}
},
/*
navBack : function (id) {
if (!id) {
// invalid parameter
jQuery.sap.log.error("navBack - parameters id must be given");
} else {
// close open popovers
if (sap.m.InstanceManager.hasOpenPopover()) {
sap.m.InstanceManager.closeAllPopovers();
}
// close open dialogs
if (sap.m.InstanceManager.hasOpenDialog()) {
sap.m.InstanceManager.closeAllDialogs();
jQuery.sap.log.info("navBack - closed dialog(s)");
}
// ... and navigate back
var app = this.getView().app;
var currentId = (app.getCurrentPage()) ? app.getCurrentPage().getId() : null;
if (currentId !== id) {
app.backToPage(id);
jQuery.sap.log.info("navBack - back to page: " + id);
}
}
}
*/
});
In Component.js I had 2 rows where I set up custom myNavBack and myNavToWithoutHash functions:
// 3a. monkey patch the router
var oRouter = this.getRouter();
oRouter.myNavBack = ui5bp.MyRouter.myNavBack; //to comment
oRouter.myNavToWithoutHash = ui5bp.MyRouter.myNavToWithoutHash; //to comment
I have started from an example of app skeleton for my app and then I have implemented the routing with the logic suggested from the framework.
This coexistence of two different methods to navigate produced the error in console. Tahnkyou #TimGerlach
After the comment of the two rows errors have vanished.

Masonry filter + infinite scroll issue

I built jQuery Masonry layout with infinite scroll and filtering.
My problem is that when a filter clicked before scrolling, the content loaded with infinite scroll is not filtered.
Is there any way to fix it?
Here is the link to check: http://www.jcvergara.com/working/
Here is the full masonry code:
$(document).ready(function(){
var $container = $('.container');
// initialize
$container.masonry({
columnWidth: 250,
itemSelector: '.item',
isFitWidth: true
});
$container.masonry( 'on', 'layoutComplete', function() {
$('.right-line').css('height', $('.container').height());
});
$('.right-line').css('height', $('.container').height());
// infinite scroll
var $container = $('#content');
$container.infinitescroll({
navSelector : "nav.posts-navigation",
nextSelector : "div.nav-previous a:first",
itemSelector : "#content div.item",
},
// trigger Masonry as a callback
function( newElements ) {
var $newElems = $( newElements );
$container.masonry( 'appended', $newElems );
// open posts in ajax
$('.post-link').click(function(){
$('.openarticle').css('display', 'block');
var post_link = $(this).attr('href');
$('#openthis').html('<div class="title"><h2>Loading..</h2><div class="text"></div>');
$('#openthis').load(post_link);
$('<a></a>', {
text: 'Close',
class: 'close',
id: 'close',
href: '#'
})
.prependTo($('.openarticle .main'))
.click(function() {
$('.openarticle').css('display', 'none');
$('#close').remove();
});
return false;
});
}
);
// filtering
$(".cat-item a").click(function(e) {
e.preventDefault();
var cut_url = "http://www.jcvergara.com/category/";
var group = $(this).attr('href');
group = group.replace(cut_url, '').slice(0,-1);
var group_class = "." + group;
$(".cat-item a.active").removeClass('active');
$(this).addClass('active');
if(group != "all") {
$(".item").hide();
$(group_class).show();
$container.masonry();
} else {
$(".item").show();
$container.masonry();
}
});
});
Try using "on" for your click function:
// filtering
$(".cat-item a").on( "click",function (e) {
e.preventDefault();
var cut_url = "http://www.jcvergara.com/category/";
var group = $(this).attr('href');
group = group.replace(cut_url, '').slice(0,-1);
var group_class = "." + group;
$(".cat-item a.active").removeClass('active');
$(this).addClass('active');
if(group != "all") {
$(".item").hide();
$(group_class).show();
$container.masonry();
} else {
$(".item").show();
$container.masonry();
}
});

Jquery datepicker keypress to trigger button

I have a datepicker that is bind to the textbox
MakeDateField: function () {
$(this).not(".dispField").datepicker({ dateFormat: 'dd/mm/yy', changeMonth: true, changeYear: true, yearRange: '-100:+20', onSelect: function () { $(this).blur(); } });
$(this).blur(function () {
$(this).val($.trim($(this).val()));
if (datePickerBlurFix == 0) {
datePickerBlurFix = 1;
if (isValidDate($(this).val()) == false) {
$(this).val(convertDate($(this).val()));
if (dateRegEx.test($(this).val()) == false && $(this).val() != '') {
if ($(this).val() != "today" && $(this).val() != "**No Access**") {
$(this).val('');
msgBox({ Msg: msgDateCheck, Title: applicationName + ' - Error', Width: 300, Type: 'warning' }, function () {
$(this).focus();
datePickerBlurFix = 0;
});
}
}
}
}
datePickerBlurFix = 0;
});
},
My problem is when I press enter, the datepicker will automatic select today date. But it doesn't go in to the following code
$("#<%=txtDateSendFrom.ClientID %>").keypress(function (event) {
if (event.which == 13) {
$("#<%=btnFilter.ClientID %>").trigger("click");
event.preventDefault();
}
});
No matter how hard I press "Enter". I think this is because it has lost focus, but if I add one $(this).focus() in to the datepicker. It also didn't work, plus the window of the datepicker will remain opened.
How can I solve this problem?
Thank You

unique form field validation in extjs4

Is there a cleaner way to define unique form field in extjs. Below is a sample code that is checking on client UID on client creation/edition. This code is working but has some bugs - for example on client creation if you enter a value that is already present in DB validator returns true until you unfocus the field.
Ext.define('AM.view.client.UniqueField', {
extend: 'Ext.form.field.Text',
alias : 'widget.uniquefield',
vtype: 'UniqueUid',
initComponent: function() {
Ext.apply(Ext.form.field.VTypes, {
UniqueUidMask : /[0-9]/i,
UniqueUid : function(val,field) {
if (val.length < 9) {
Ext.apply(Ext.form.field.VTypes, {
UniqueUidText: 'Company ID is too small'
});
return false;
} else {
var paste=/^[0-9_]+$/;
if (!paste.test(val)) {
Ext.apply(Ext.form.field.VTypes, {
UniqueUidText: 'Ivalid characters'
});
return false;
} else {
var mask = new Ext.LoadMask(field.up('form'),{msg:'Please wait checking....'});
mask.show();
var test= 0;
var store = Ext.create('AM.store.Clients');
store.load({params:{'uid':val, 'id': Ext.getCmp('client_id').getValue()}});
store.on('load', function(test) {
mask.hide();
if(parseInt(store.getTotalCount())==0){
this.uniqueStore(true);
}else{
Ext.apply(Ext.form.field.VTypes, {
UniqueUidText: 'Company ID is already present'
});
this.uniqueStore(false);
}
},this)
return true;
}
}}
},this);
this.callParent(arguments);
},
uniqueStore: function(is_error){
Ext.apply(Ext.form.field.VTypes, {
UniqueUidMask : /[0-9]/i,
UniqueUid : function(val,field) {
if (val.length < 9) {
Ext.apply(Ext.form.field.VTypes, {
UniqueUidText: 'Company ID is too small'
});
return false;
} else {
var paste=/^[0-9_]+$/;
if (!paste.test(val)) {
Ext.apply(Ext.form.field.VTypes, {
UniqueUidText: 'Ivalid characters'
});
return false;
} else {
var mask = new Ext.LoadMask(field.up('form'),{msg:'Please wait checking....'});
mask.show();
var store = Ext.create('AM.store.Clients');
store.load({params:{'uid':val, 'id': Ext.getCmp('client_id').getValue()}});
store.on('load', function(test) {
mask.hide();
if(parseInt(store.getTotalCount())==0){
this.uniqueStore(true);
}else{
this.uniqueStore(false);
}
},this)
return is_error;
}
}}
},this);
}
});
How about using server side validation?
I answered to similar issue here: extjs4 rails 3 model validation for uniqueness
Obviously you can change it to use "ajax" instead of "rest" proxy.