How to handle a drag-event within Google Earth plugin? - drag-and-drop

My javascript is very weak.
Is it possible to modify the same code below to do the following:
Make the objects loaded draggable
When the object is dropped, an ajax request to something like:
http://.../moveTo?lat=new_lat&long=new_long&id=some_way_to_uniquely_id_the_object
Any advice to offer?
Sample Code:
var ge;
// store the object loaded for the given file... initially none of the objects
// are loaded, so initialize these to null
var currentKmlObjects = {
'red': null,
'yellow': null,
'green': null
};
google.load("earth", "1");
function init() {
// Create checkboxes
var content = document.getElementById('content');
var inputHTML = 'Placemarks:<br/>';
inputHTML += '<input type="checkbox" id="kml-red-check" onclick="toggleKml(\'red\');"/>' +
'<label for="kml-red-check">Red</label>' +
'<input type="checkbox" id="kml-yellow-check" onclick="toggleKml(\'yellow\');"/>' +
'<label for="kml-yellow-check">Yellow</label>' +
'<input type="checkbox" id="kml-green-check" onclick="toggleKml(\'green\');"/>' +
'<label for="kml-green-check">Green</label>';
content.innerHTML = inputHTML;
google.earth.createInstance('content', initCB, failureCB);
}
function initCB(instance) {
ge = instance;
ge.getWindow().setVisibility(true);
// add a navigation control
ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO);
// add some layers
ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, true);
ge.getLayerRoot().enableLayerById(ge.LAYER_ROADS, true);
// fly to Santa Cruz
var la = ge.createLookAt('');
la.set(37, -122,
0, // altitude
ge.ALTITUDE_RELATIVE_TO_GROUND,
0, // heading
0, // straight-down tilt
5000 // range (inverse of zoom)
);
ge.getView().setAbstractView(la);
// if the page loaded with checkboxes checked, load the appropriate
// KML files
if (document.getElementById('kml-red-check').checked)
loadKml('red');
if (document.getElementById('kml-yellow-check').checked)
loadKml('yellow');
if (document.getElementById('kml-green-check').checked)
loadKml('green');
document.getElementById('installed-plugin-version').innerHTML =
ge.getPluginVersion().toString();
}
function failureCB(errorCode) {
}
function toggleKml(file) {
// remove the old KML object if it exists
if (currentKmlObjects[file]) {
ge.getFeatures().removeChild(currentKmlObjects[file]);
currentKmlObject = null;
}
// if the checkbox is checked, fetch the KML and show it on Earth
var kmlCheckbox = document.getElementById('kml-' + file + '-check');
if (kmlCheckbox.checked)
loadKml(file);
}
function loadKml(file) {
var kmlUrl = 'http://earth-api-samples.googlecode.com/svn/trunk/' +
'examples/static/' + file + '.kml';
// fetch the KML
google.earth.fetchKml(ge, kmlUrl, function(kmlObject) {
// NOTE: we still have access to the 'file' variable (via JS closures)
if (kmlObject) {
// show it on Earth
currentKmlObjects[file] = kmlObject;
ge.getFeatures().appendChild(kmlObject);
} else {
// bad KML
currentKmlObjects[file] = null;
alert('Bad KML');
// uncheck the box
document.getElementById('kml-' + file + '-check').checked = '';
}
});
}
google.setOnLoadCallback(init);
For bonus points, can I get the kml to be reloaded afterwards?

To make the objects draggable you need to set up some event listeners and handle the movement in the callback function. I presume the objects you wish to drag are place-marks (KmlPlacemark) if so you need something like this...(NB: This is untested and written here so there could be some typos.)
var dragging = false; // the object being dragged
var url = "http://.../moveTo?"; // path to your cgi script
function init() {
// Rest of your method body...
google.earth.addEventListener(ge.getGlobe(), "mousedown", function(e)
{
// if it is a place mark
if(e.getTarget().getType() == 'KmlPlacemark')
{
// set it as the dragging target
dragging = e.getTarget();
}
});
google.earth.addEventListener(ge.getGlobe(), "mouseup", function(e)
{
// drop on mouse up (if we have a target)
if(dragging) {
// build the query string
// ...you could use getName or getSnippet rather than getId
var query = "lat=" + dragging.getGeometry().getLatitude() +
"&long=" + dragging.getGeometry().getLongitude() +
"&id=" + dragging.getId();
// send the query to the url
httpPost(url, query);
// clear the dragging target
dragging = false;
}
});
google.earth.addEventListener(ge.getGlobe(), "mousemove", function(e)
{
// when the mouse moves (if we have a dragging target)
if(dragging) {
// stop any balloon opening
e.preventDefault();
// drag the object
// i.e. set the placemark location to cursor the location
dragging.getGeometry().setLatLng(e.getLatitude(), e.getLongitude());
}
});
}
// send a HTTP POST request
// could use jQuery, etc....
function httpPost(url, query) {
var httpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.httpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.httpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.httpReq .open('POST', url, true);
self.httpReq .setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.httpReq .onreadystatechange = function() {
if (self.httpReq .readyState == 4) {
// do something...
alert(self.httpReq.responseText);
}
}
self.httpReq.send(query);
}

Related

Asynchronous function in SAPUI5

I'm using a function to open a dialog in SAPUI5. While this dialog is opening, some data should be set in the local storage of the browser. However, when I add the local storage function, it takes a few seconds to open the dialog.
Is there a way I can make the local storage async? I tried putting the function of the local storage after the opening of the dialog. But it doesn't change anything..
/* WHEN THE USER CLICKS ON AN ASSIGNMENT IN THE CALENDAR */
onClickAssignment: function(oEvent) {
var oAppointment = oEvent.getParameter("appointment");
this.lastAppointment = oAppointment;
if (oAppointment) {
var key = this.byId("PC1").getViewKey();
if (key === "Month") {
if (!this._oDetailsDialog || this._oDetailsDialog === null) {
// show assignment dialog
this._oDetailsDialog = sap.ui.xmlfragment(this.fragmentDetailsId, "be.xxxxxxxxxxx.fragment.viewAssignment", this);
this.getView().addDependent(this._oDetailsDialog);
}
} else {
if (!this._oDetailsDialog || this._oDetailsDialog === null) {
// show subassignment dialog
this._oDetailsDialog = sap.ui.xmlfragment(this.fragmentDetailsId, "be.xxxxxxxxxxx.fragment.viewSubassignment", this);
this.getView().addDependent(this._oDetailsDialog);
}
}
this.oAppBC = oAppointment.getBindingContext();
this._oDetailsDialog.setBindingContext(this.oAppBC);
this._oDetailsDialog.open();
this.lastClickedAssignment = oAppointment.getProperty("assignment");
this.lastClickedSubassignment = oAppointment.getProperty("subassignment");
//SET LOCAL STORAGE
// var stringifiedContext = CircularJSON.stringify(oAppointment.getBindingContext());
// var stringifiedAssignment = CircularJSON.stringify(oAppointment.getProperty("assignment"));
// var stringifiedSubassignment = CircularJSON.stringify(oAppointment.getProperty("subassignment"));
// this.setLocalStorage("context", stringifiedContext);
// this.setLocalStorage("assignment", stringifiedAssignment);
// this.setLocalStorage("subassignment", stringifiedSubassignment);
}
},
You can detach execution of that part of the code from the main execution thread by wrapping it into setTimeout:
/* WHEN THE USER CLICKS ON AN ASSIGNMENT IN THE CALENDAR */
onClickAssignment: function(oEvent) {
var oAppointment = oEvent.getParameter("appointment");
this.lastAppointment = oAppointment;
if (oAppointment) {
var key = this.byId("PC1").getViewKey();
if (key === "Month") {
if (!this._oDetailsDialog || this._oDetailsDialog === null) {
// show assignment dialog
this._oDetailsDialog = sap.ui.xmlfragment(this.fragmentDetailsId, "be.xxxxxxxxxxx.fragment.viewAssignment", this);
this.getView().addDependent(this._oDetailsDialog);
}
} else {
if (!this._oDetailsDialog || this._oDetailsDialog === null) {
// show subassignment dialog
this._oDetailsDialog = sap.ui.xmlfragment(this.fragmentDetailsId, "be.xxxxxxxxxxx.fragment.viewSubassignment", this);
this.getView().addDependent(this._oDetailsDialog);
}
}
this.oAppBC = oAppointment.getBindingContext();
this._oDetailsDialog.setBindingContext(this.oAppBC);
this._oDetailsDialog.open();
this.lastClickedAssignment = oAppointment.getProperty("assignment");
this.lastClickedSubassignment = oAppointment.getProperty("subassignment");
setTimeout(function () {
//SET LOCAL STORAGE
var stringifiedContext = CircularJSON.stringify(oAppointment.getBindingContext());
var stringifiedAssignment = CircularJSON.stringify(oAppointment.getProperty("assignment"));
var stringifiedSubassignment = CircularJSON.stringify(oAppointment.getProperty("subassignment"));
this.setLocalStorage("context", stringifiedContext);
this.setLocalStorage("assignment", stringifiedAssignment);
this.setLocalStorage("subassignment", stringifiedSubassignment);
});
}
},
OR you can also do it after open:
this._oDetailsDialog.attachEventOnce('afterOpen', function () {
//SET LOCAL STORAGE
// ...
});

NativeScript - how can I filter an observable array with SearchBar?

Hi I'm trying to filter an observable array of data fetched via a HTTP request on keypress of the SearchBar.
I managed to get the SearchBar property change to work but I can't seem to figure out what I'm doing wrong in the filtering logic.
Ideally I want to update the list as I type in the search term in the SearchBar. I've searched the API on the Telerik site, there wasn't really any examples I could find.
XML
<Page loaded="pageLoaded">
<ActivityIndicator busy="{{ isLoading }}" />
<ActionBar title="People">
</ActionBar>
<GridLayout>
<StackLayout>
<SearchBar id="searchBar" hint="Search for someone"></SearchBar>
<ListView items="{{ peopleList }}" itemTap="showDetail">
<ListView.itemTemplate>
<StackLayout>
<Label text="{{ fullName }}" horiztonalAlignment="left" verticalAlignment="center"></Label>
<Label text="{{ company }}" class="info"></Label>
</StackLayout>
</ListView.itemTemplate>
</ListView>
</StackLayout>
</GridLayout>
</Page>
JS
var frames = require("ui/frame");
var Observable = require("data/observable").Observable;
var PeopleListViewModel = require("../../shared/people-viewModel");
var activityIndicatorModule = require("ui/activity-indicator");
var page;
var userkey;
var peopleList = new PeopleListViewModel([]);
var pageData = new Observable({ peopleList: peopleList });
exports.pageLoaded = function(args) {
page = args.object;
page.bindingContext = pageData;
userkey = userkey || page.navigationContext.userkey;
peopleList.load(userkey); // fetch data from the backend
var searchBar = page.getViewById("searchBar");
searchBar.on("propertyChange", function (args) {
var searchText = args.object.text;
if (searchText === "") {
// NOT SURE WHAT TO DO HERE.
} else {
peopleList.filter(function (element, index, array) {
// DOESN"T WORK PROPERLY
console.log("element: ", JSON.stringify(element));
return element.fullName == searchText;
});
console.log("Text types: ", searchText);
}
});
};
exports.showDetail = function(args) {
var person = peopleList.getItem(args.index);
var navigateEntry = {
moduleName: "views/people/people-detail",
context: { person: person },
animated: false
};
frames.topmost().navigate(navigateEntry);
};
PeopleListViewModel.js
var config = require("./config");
var fetchModule = require("fetch");
var ObservableArray = require("data/observable-array").ObservableArray;
function PeopleListViewModel(people) {
var viewModel = new ObservableArray(people);
viewModel.load = function (userKey) {
return fetchModule.fetch(config.baseUrl + "/api/people/all/" + userKey)
.then(function (response) {
return response.json();
})
.then(function (data) {
data.forEach(function (person) {
viewModel.push(person);
});
}, function (error) {
console.log("Error: ", error);
});
};
viewModel.empty = function () {
while (viewModel.length) {
viewModel.pop();
}
};
return viewModel;
}
function handleErrors(response) {
if (!response.ok) {
console.log("Error occurred");
}
}
module.exports = PeopleListViewModel;
Updated people-list
var frames = require("ui/frame");
var Observable = require("data/observable").Observable;
var ObservableArray = require("data/observable-array").ObservableArray;
var PeopleListViewModel = require("../../shared/people-viewModel");
var activityIndicatorModule = require("ui/activity-indicator");
var page;
var userkey;
var peopleList = new PeopleListViewModel([]);
var pageData = new Observable({ peopleList: peopleList });
var resultList = new ObservableArray([]);
exports.pageLoaded = function(args) {
page = args.object;
page.bindingContext = pageData;
userkey = userkey || page.navigationContext.userkey;
peopleList.load(userkey);
var searchBar = page.getViewById("searchBar");
searchBar.on("propertyChange", function (args) {
var searchText = args.object.text;
if (searchText === "") {
} else {
while (resultList.length > 0) {
resultList.pop();
}
peopleList.forEach(function (element) {
if (element.fullName === searchText) {
resultList.push(element);
}
});
}
});
};
I had the same issue. If you want to filter your data after every character has changed in search-bar you can try my solution.
Definitions
My playerList is your peopleList. This is the data from view-model.
resultList is an array where the data will be pushed.
var observableArrayModule = require("data/observable-array").ObservableArray;
var playerList = new PlayerListViewModel([]);
var resultList = new observableArrayModule([]);
var pageData = new observableModule.Observable({
resultList: resultList,
player: ""
});
Inside expors.loaded()
page = args.object;
searchBar = page.getViewById("search-bar");
page.bindingContext = pageData;
Load Initial Data - inside expors.loaded()
We are loading initial data when user navigates to the screen for the first time. We are also pushing the same data to resultList since we are using {{resultList}} in xml. You can add loadingIndicator while the list is populated.
playerList
.load()
.then(function() {
setTimeout(function() {
playerList.forEach(function (element) {
pageData.resultList.push(element);
});
}, 1000);
})
.catch(function(error) {
dialogsModule.alert({
message: "An error occurred while loading players.",
okButtonText: "OK"
});
});
Clear autofocus - inside expors.loaded()
This is to prevent keyboard from opening on initial screen navigation.
if (searchBar.ios) {
searchBar.ios.endEditing(true);
} else if (searchBar.android) {
searchBar.android.clearFocus();
}
Search data when character has changed - inside expors.loaded()
I am calling filter functionality. Lodash _.debounce function is used to delay looping through resultList array. Without it, the app would loop every time letter is typed. Now we are waiting for user to stop typing to start looping.
searchBar.on('propertyChange', _.debounce(searchList, 500));
searchList Function
This is the actual loop. You can change element.name for your needs.
function searchList(args) {
var searchText = args.object.text;
while(resultList.length > 0) {
resultList.pop();
}
playerList.forEach(function (element) {
if (element.name.toLowerCase().indexOf(searchText) >= 0) {
resultList.push(element);
}
});
}
Hide keyboard if search-bar is cleared - inside exports.loaded()
And finally we want to hide the keyboard if user clears the search-bar.
searchBar.on(searchBarModule.SearchBar.clearEvent, function (args) {
setTimeout(function() {
searchBar.dismissSoftInput();
}, 10);
});
PS
You probably solved your issue, but this could help someone else in the future.
Okay so your problem is a Javascript problem than a NativeScript problem. For the sake of this problem, think of observable arrays as just your ordinary arrays.
In your JS you're creating a new PeopleListViewModel which you're then attaching to the bindingContext via the pageData object. So far so good. Then you're calling the load method on the PeopleListViewModel (It returns a promise which you're not really doing anything with but for this specific problem it doesn't matter).
However, when text is inputed you're not really doing anything. This is your code:
peopleList.filter(function (element, index, array) {
// DOESN"T WORK PROPERLY
console.log("element: ", JSON.stringify(element));
return element.fullName == searchText;
});
peopleList is an instance of PeopleListViewModel which returns an ObservableArray. The ObservableArray does indeed have a method called filter (which works just like filter of a regular array. Check out the NativeScript documentation and Javascript documentation of filter).
What you need to understand here is that filter returns a new array with the filtered results. Doing peopleList.filter() will send that new array into empty space. You want to var yourNewFilteredArray = peopleList.filter(). But you don't really want to redefine the array bound to the binding context, you want to modify the content of it.
Here's an example of how you could do that:
/*
* Attach a new obsersable array to the binding context.
* you can prepopulate it with the data from the
* PeopleListViewModel if you want to
*/
var resultList = new ObservableArray([]);
var pageData = new Observable({ resultList: resultList });
/*
* Then on search/filter you want to modify this new
* array. Here I first remove every item in it and then
* push matching items to it.
*/
searchBar.on("propertyChange", function (args) {
var searchText = args.object.text;
// ...
while(resultList.length > 0) {
resultList.pop();
}
peopleList.forEach(function (element) {
if (element.fullName === searchText) {
resultList.push(element);
}
});
});

Google maps api v2 get polygon coordinate

I am a bit of a beginner at google maps api. I managed to let the user to draw a polygon on the map and then I want to get the coordinates on the drew polygon.
I have used the following segment of code but it gave me the following error Uncaught TypeError: Object [object Object] has no method 'getPath'
this is the code that I used
function startShape() {
initialize();
document.getElementById('lat').disabled = true;
document.getElementById('lng').disabled = true;
var polygon = new GPolygon([],"ff0000", 2, 0.7,"ff0000",0.2);
startDrawing(polygon, "Shape " + (++shapeCounter_), function() {
var cell = this;
var area = polygon.getArea();
cell.innerHTML = (Math.round(area / 10000) / 100) + "km<sup>2</sup>";
});
showcoor(polygon);
}
function startDrawing(poly, name, onUpdate) {
map.addOverlay(poly);
poly.enableDrawing(options);
poly.enableEditing({onEvent: "mouseover"});
poly.disableEditing({onEvent: "mouseout"});
GEvent.addListener(poly, "endline", function() {
//var cells = addFeatureEntry(name, color);
//GEvent.bind(poly, "lineupdated", cells.desc, onUpdate);
GEvent.addListener(poly, "click", function(latlng, index) {
if (typeof index == "number") {
poly.deleteVertex(index);
}
});
});
}
function showcoor (poly) {
GEvent.addListener(poly, "endline", function() {
GEvent.addListener(poly, "click", function() {
var str;
var vertices = this.getPath();
for (var i =0; i < vertices.length; i++) {
var xy = vertices.getAt(i);
str += xy.lat() +"," + xy.lng()+"<br />";
}
alert (str);
});
});
}
There is no getPath method on the GPolygon object. See the GPolygon reference.
Instead, you'll need to use getVertexCount() and getVertex(i).
for (var i = 0, I = this.getVertexCount(); i < I; ++i) {
var xy = this.getVertex(i);
str += xy.lat() + ', ' + xy.lng() + '<br />';
}

Use currentLocation along with a business search in bing map API

I was currently at this site which shows how to implement business search using the bing map api. But what I am trying to implement is, first the map should get your current location and search for type of business nearby, let's say Restaurant or Check Cashing place.
My current page has the current location working but now how I implement the FindNearBy function with my page?
P.s. I want the search to already take place for the user without having to enter a search text, so the map should load up with current location and right next to it should list all or maybe the closest 5 restaurant nearby.
Not with Bing Maps...you need the Bing Phonebook API to do this.
I can get you part of the way there. The below example combines the use of both the Bing Maps API and the Bing Phonebook API) I just submitted a similar question about how to find the type of business, however...I'm not sure there's a wayto do this :/ (Below example searches for all Starbucks in the area ...of course, some HTML integration is required.
var _map;
var _appId;
$(document).ready(function () {
if (Modernizr.geolocation) {
$(".geofallback").hide();
}
else {
$(".geofallback").show();
}
$.post("Home/GetBingMapsKey", { "func": "GetBingMapsKey" }, function (data) {
// Create a Bing map
_map = new Microsoft.Maps.Map(document.getElementById("map"),
{ credentials: data }); //, mapTypeId: Microsoft.Maps.MapTypeId.ordnanceSurvey
});
// Get the current position from the browser
if (!navigator.geolocation) {
$("#results").html("This browser doesn't support geolocation, please enter an address");
}
else {
$.post("Home/GetBingKey", { "func": "GetBingKey" }, function (data) {
_appId = data;
});
navigator.geolocation.getCurrentPosition(onPositionReady, onError);
navigator.geolocation.getCurrentPosition(Search, onError);
}
});
function onPositionReady(position) {
// Apply the position to the map
var location = new Microsoft.Maps.Location(position.coords.latitude,
position.coords.longitude);
_map.setView({ zoom: 18, center: location });
// Add a pushpin to the map representing the current location
var pin = new Microsoft.Maps.Pushpin(location);
_map.entities.push(pin);
}
function onError(err) {
switch (err.code) {
case 0:
alert("Unknown error :(");
break;
case 1:
alert("Location services are unavailable per your request.");
break;
case 2:
alert("Location data is unavailable.");
break;
case 3:
alert("The location request has timed out. Please contact support if you continue to experience issues.");
break;
}
}
function Search(position) {
// note a bunch of this code uses the example code from
// Microsoft for the Phonebook API
var requestStr = "http://api.bing.net/json.aspx?"
// Common request fields (required)
+ "AppId=" + _appId
+ "&Query=starbucks"
+ "&Sources=Phonebook"
// Common request fields (optional)
+ "&Version=2.2"
+ "&Market=en-us"
+ "&UILanguage=en"
+ "&Latitude=" + position.coords.latitude
+ "&Longitude=" + position.coords.longitude
+ "&Radius=100.0"
+ "&Options=EnableHighlighting"
// Phonebook-specific request fields (optional)
// Phonebook.Count max val is 25
+ "&Phonebook.Count=25"
+ "&Phonebook.Offset=0"
// YP = Commercial Entity, WP = Residential
+ "&Phonebook.FileType=YP"
+ "&Phonebook.SortBy=Distance"
// JSON-specific request fields (optional)
+ "&JsonType=callback"
+ "&JsonCallback=?";
$.getJSON(requestStr, function (data) {
SearchCompleted(data);
});
}
function FormatBingQuery(appId, latitude ) {
}
function SearchCompleted(response) {
var errors = response.SearchResponse.Errors;
if (errors != null) {
// There are errors in the response. Display error details.
DisplayErrors(errors);
}
else {
// There were no errors in the response. Display the
// Phonebook results.
DisplayResults(response);
}
}
function DisplayResults(response) {
var output = document.getElementById("output");
var resultsHeader = document.createElement("h4");
var resultsList = document.createElement("ul");
output.appendChild(resultsHeader);
output.appendChild(resultsList);
var results = response.SearchResponse.Phonebook.Results;
// Display the results header.
resultsHeader.innerHTML = "Bing API Version "
+ response.SearchResponse.Version
+ "<br />Phonebook results for "
+ response.SearchResponse.Query.SearchTerms
+ "<br />Displaying "
+ (response.SearchResponse.Phonebook.Offset + 1)
+ " to "
+ (response.SearchResponse.Phonebook.Offset + results.length)
+ " of "
+ response.SearchResponse.Phonebook.Total
+ " results<br />";
// Display the Phonebook results.
var resultsListItem = null;
var resultStr = "";
for (var i = 0; i < results.length; ++i) {
resultsListItem = document.createElement("li");
resultsList.appendChild(resultsListItem);
//loc is specific to my C# object
var loc = new Array();
loc[0] = results[i].Longitude;
loc[1] = results[i].Latitude;
var address = {
AddressLine1: results[i].Address,
City: results[i].City,
State: results[i].StateOrProvince,
PostalCode: results[i].PostalCode,
Latitude: results[i].Latitude,
Longitude: results[i].Longitude,
Country: results[i].CountryOrRegion,
ID: results[i].UniqueId
};
//this part is specific to my project to return the
//address results so I can store them (since my
//implementation is a demonstration of how to
//use the MongoDB geoNear() functionality
$.ajax({
url: "/Home/AddAddressToCollection",
type: 'post',
data: JSON.stringify(address),
contentType: 'application/json',
dataType: 'json'
});
resultStr = results[i].Business
+ "<br />"
+ results[i].Address
+ "<br />"
+ results[i].City
+ ", "
+ results[i].StateOrProvince
+ "<br />"
+ results[i].PhoneNumber
+ "<br />Average Rating: "
+ results[i].UserRating
+ "<br /><br />";
// Replace highlighting characters with strong tags.
resultsListItem.innerHTML = ReplaceHighlightingCharacters(
resultStr,
"<strong>",
"</strong>");
}
}
function ReplaceHighlightingCharacters(text, beginStr, endStr) {
// Replace all occurrences of U+E000 (begin highlighting) with
// beginStr. Replace all occurrences of U+E001 (end highlighting)
// with endStr.
var regexBegin = new RegExp("\uE000", "g");
var regexEnd = new RegExp("\uE001", "g");
return text.replace(regexBegin, beginStr).replace(regexEnd, endStr);
}
function DisplayErrors(errors) {
var output = document.getElementById("output");
var errorsHeader = document.createElement("h4");
var errorsList = document.createElement("ul");
output.appendChild(errorsHeader);
output.appendChild(errorsList);
// Iterate over the list of errors and display error details.
errorsHeader.innerHTML = "Errors:";
var errorsListItem = null;
for (var i = 0; i < errors.length; ++i) {
errorsListItem = document.createElement("li");
errorsList.appendChild(errorsListItem);
errorsListItem.innerHTML = "";
for (var errorDetail in errors[i]) {
errorsListItem.innerHTML += errorDetail
+ ": "
+ errors[i][errorDetail]
+ "<br />";
}
errorsListItem.innerHTML += "<br />";
}
}
// Bonus: In case you want to provide directions
// for how to get to a selected entity
// _map.getCredentials(function (credentials) {
// $.getJSON('http://dev.virtualearth.net/REST/V1/Routes/driving?' + 'wp.0=' + lat1 + ',' + lon1 + '&wp.1=' + lat2 + ',' + lon2 + '&distanceUnit=mi&optmz=distance&key=' + credentials + '&jsonp=?&s=1',
// function (result) {
// if (result.resourceSets[0].estimatedTotal > 0) {
// var distance = result.resourceSets[0].resources[0].travelDistance;
// }
// else {
// $("#results").html("Oops! It appears one or more of the addresses you entered are incorrect. :( ");
// }
// });
// });
//Tie into a function that shows an input field
//for use as a fallback in case cannot use HTML5 geoLocation
//$(document).ready(function () {
// $("#btnFindLocation").click(function () {
// //check user has entered something first
// if ($("#txtAddress").val().length > 0) {
// //send location query to bing maps REST api
// _map.getCredentials(function (credentials) {
// $.getJSON('http://dev.virtualearth.net/REST/v1/Locations?query=' + $("#txtAddress").val() + '&key=' + credentials + '&jsonp=?&s=1',
// function (result) {
// if (result.resourceSets[0].estimatedTotal > 0) {
// var loc = result.resourceSets[0].resources[0].point.coordinates;
// $("#lat").val(loc[0]);
// $("#lon").val(loc[1]);
// var location = new Microsoft.Maps.Location(loc[0],
// loc[1]);
// _map.setView({ zoom: 18, center: location });
// // Add a pushpin to the map representing the current location
// var pin = new Microsoft.Maps.Pushpin(location);
// _map.entities.push(pin);
// }
// else {
// $("#results").html("sorry that address cannot be found");
// }
// });
// });
// }
// else {
// $("#results").html("please enter an address");
// }
// });
//});

multiple file upload using html5 drag-and-drop fails as multiple files get same content

I need to transfer all the files dropped on an element to a server using HTML5 drag and drop.
I provided the corresponding js code below. I have a servlet in the server side to collect the files and put it in a folder. This is working fine if I drop 1 or 2 files on the page. But, if i drop 4-10 files, all the files are getting created in the server but multiple files are set to same content and some files content is 0K.
Can any of you please tell me how to achieve the correct behavior.
My requirement is similar to gmail attachments!!
Any solution which makes a sequential upload of files is much appreciable.
/*
* Upload files to the server using HTML 5 Drag and drop from the folders on your local computer
*/
function uploader(place, status, target, show) {
// Upload image files
upload = function(file) {
// Firefox 3.6, Chrome 6, WebKit
if(window.FileReader) {
// Once the process of reading file
this.loadEnd = function() {
bin = reader.result;
xhr = new XMLHttpRequest();
xhr.open('POST', target+'?up=true', false);
var body = bin;
xhr.setRequestHeader('content-type', 'multipart/form-data;');
xhr.setRequestHeader("file-name", file.name );
xhr.setRequestHeader("mime-type", file.type );
// Firefox 3.6 provides a feature sendAsBinary ()
if(xhr.sendAsBinary != null) {
xhr.sendAsBinary(body);
// Chrome 7 sends data but you must use the base64_decode on the PHP side
} else {
xhr.open('POST', target+'?up=true&base64=true', true);
xhr.setRequestHeader('UP-FILENAME', file.name);
xhr.setRequestHeader('UP-SIZE', file.size);
xhr.setRequestHeader('UP-TYPE', file.type);
xhr.send(window.btoa(bin));
}
if (show) {
var newFile = document.createElement('div');
newFile.innerHTML = 'Loaded : '+file.name+' size '+file.size+' B';
document.getElementById(show).appendChild(newFile);
}
if (status) {
document.getElementById(status).innerHTML = 'Loaded : 100%<br/>Next file ...';
}
};
// Loading errors
this.loadError = function(event) {
switch(event.target.error.code) {
case event.target.error.NOT_FOUND_ERR:
document.getElementById(status).innerHTML = 'File not found!';
break;
case event.target.error.NOT_READABLE_ERR:
document.getElementById(status).innerHTML = 'File not readable!';
break;
case event.target.error.ABORT_ERR:
break;
default:
document.getElementById(status).innerHTML = 'Read error.';
}
};
// Reading Progress
this.loadProgress = function(event) {
if (event.lengthComputable) {
var percentage = Math.round((event.loaded * 100) / event.total);
document.getElementById(status).innerHTML = 'Loaded : '+percentage+'%';
}
};
// Preview images
this.previewNow = function(event) {
bin = preview.result;
var img = document.createElement("img");
img.className = 'addedIMG';
img.file = file;
img.src = bin;
document.getElementById(show).appendChild(img);
};
reader = new FileReader();
// Firefox 3.6, WebKit
if(reader.addEventListener) {
reader.addEventListener('loadend', this.loadEnd, false);
if (status != null)
{
reader.addEventListener('error', this.loadError, false);
reader.addEventListener('progress', this.loadProgress, false);
}
// Chrome 7
} else {
reader.onloadend = this.loadEnd;
if (status != null)
{
reader.onerror = this.loadError;
reader.onprogress = this.loadProgress;
}
}
var preview = new FileReader();
// Firefox 3.6, WebKit
if(preview.addEventListener) {
preview.addEventListener('loadend', this.previewNow, false);
// Chrome 7
} else {
preview.onloadend = this.previewNow;
}
// The function that starts reading the file as a binary string
reader.readAsBinaryString(file);
// Preview uploaded files
if (show) {
preview.readAsDataURL(file);
}
// Safari 5 does not support FileReader
} else {
xhr = new XMLHttpRequest();
xhr.open('POST', target+'?up=true', true);
xhr.setRequestHeader('UP-FILENAME', file.name);
xhr.setRequestHeader('UP-SIZE', file.size);
xhr.setRequestHeader('UP-TYPE', file.type);
xhr.send(file);
if (status) {
document.getElementById(status).innerHTML = 'Loaded : 100%';
}
if (show) {
var newFile = document.createElement('div');
newFile.innerHTML = 'Loaded : '+file.name+' size '+file.size+' B';
document.getElementById(show).appendChild(newFile);
}
}
};
// Function drop file
this.drop = function(event) {
event.preventDefault();
var dt = event.dataTransfer;
var files = dt.files;
for (var i = 0; i<files.length; i++) {
var file = files[i];
upload(file);
}
};
// The inclusion of the event listeners (DragOver and drop)
this.uploadPlace = document.getElementById(place);
this.uploadPlace.addEventListener("dragover", function(event) {
event.stopPropagation();
event.preventDefault();
}, true);
this.uploadPlace.addEventListener("drop", this.drop, false);
}
Thank you.
I spent sometimes this morning in analyzing the same code from html5uploader. With some lucks, I found the root cause.
Change reader = new FileReader(); to var reader = new FileReader(); should solve the issue.
I bet this is because javascripts behaviour of auto-declaring undeclared variable as global variable. This caused the reader variable being reused by all the uploade(file) calls when more than one file is dropped to the browser.
Cheers!