Adding Multiple Custom Markers to Bing Maps (API) example - c#

I've started with this example:
https://code.msdn.microsoft.com/bing/Using-the-Bing-Maps-V8-Web-07e21f3a#content
Which basically gives a form with a search option and present the search result in a html file.
Now I'm trying to add an array of items instead of one to the html file, to show these.
But I can't seem to understand how to get the html file to capture the list of addresses from the Form1.cs file with a button click
I've added this to the form:
private void GroupBtn_Click(object sender, EventArgs e)
{
var pushpinInfos = new[] {
new { lat = 41.80584, lng = 21.15498, title = "Salmon Market", description = "Kipper Gostivar", icon = "http://icons.iconarchive.com/icons/icons-land/vista-map-markers/24/Map-Marker-Marker-Inside-Chartreuse-icon.png" },
new { lat = 42.000900, lng = 21.466440, title = "Market", description = "Gostivar", icon = "https://i-msdn.sec.s-msft.com/dynimg/IC488534.jpeg" }
};
MyWebBrowser.Document.InvokeScript("SetMap", new object[] { pushpinInfos });
}
And this to the html file:
function SetMap(addresses) {
//Create an infobox at the center of the map but don't show it.
infobox = new Microsoft.Maps.Infobox(map.getCenter(), {
visible: false
});
//Assign the infobox to a map instance.
infobox.setMap(map);
pinLayer = new Microsoft.Maps.EntityCollection();
map.entities.push(pinLayer);
var pins1 = JSON.stringify(addresses);
// alert(pins1);
$.each(JSON.parse(pins1), function (key, pinJson) {
var position = new Microsoft.Maps.Location(pinJson.lat, pinJson.lng);
// Creates a Pushpin
var pin = new Microsoft.Maps.Pushpin(position, { text: pinJson.Title, icon: 'images/map_pin_13.png', typeName: 'sampleCustom' });
//Store some metadata with the pushpin.
pin.metadata = {
title: 'Pin',
description: 'Discription for pin'
};
//Add a click event handler to the pushpin.
Microsoft.Maps.Events.addHandler(pin, 'click', pushpinClicked);
//Add pushpin to the map.
map.entities.push(pin);
pinLayer.push(pin);
});
}
But it doesn't work, and I can't seem to debug the html form.
So my questions are:
1) Isn't there a way to debug the html part?
2) Where did i go wrong with trying to show the 2 addresses on the map?

A couple of issues in your code:
You create a pin layer, but are adding the pins directly to the map and the layer. This will cause an issue.
Your pin layer is using the deprecated EntityCollection class and map.entities. Use map.layers and Microsoft.Maps.Layer
Pushpin's don't have a typeName option. That was a feature in an old map control and not available in the latest version as rendering happens on an HMTL5 canvas which doesn't support CSS styles.
Minor thing, but when using a layer, add events to it rather than individual shapes, it helps with performance.
Here is a modified version of your code:
function SetMap(addresses) {
//Create an infobox at the center of the map but don't show it.
infobox = new Microsoft.Maps.Infobox(map.getCenter(), {
visible: false
});
//Assign the infobox to a map instance.
infobox.setMap(map);
pinLayer = new Microsoft.Maps.Layer();
map.layers.insert(pinLayer);
//Add a click event handler to the pin layer.
Microsoft.Maps.Events.addHandler(pinLayer, 'click', pushpinClicked);
var pins1 = JSON.stringify(addresses);
// alert(pins1);
$.each(JSON.parse(pins1), function (key, pinJson) {
var position = new Microsoft.Maps.Location(pinJson.lat, pinJson.lng);
// Creates a Pushpin
var pin = new Microsoft.Maps.Pushpin(position, { text: pinJson.Title, icon: 'images/map_pin_13.png', typeName: 'sampleCustom' });
//Store some metadata with the pushpin.
pin.metadata = {
title: 'Pin',
description: 'Discription for pin'
};
//Add pushpin to the map.
pinLayer.add(pin);
});
}

Related

Binding a HTML control into a stacklayout using xamarin forms

Being a newbie to Xamrin I am struggling to adding some HTML to a StackLayout via Xamarin Forms. I have tried quite a few things and had a Google around.
Firstly I can't work out which bindable object I am supposed to be using. As I cannot find a straight answer on Google/Xamarin I am going to assume this is not as easy I was hoping.
var nameEntry = new Label ();
nameEntry.SetBinding (Label.TextProperty, "Club.ClubName");
var webView = new WebView ();
webView.SetBinding ( ??? , "Club.Description");
var content = new StackLayout {
Children = {
nameEntry,
???
}
};
I am not sure if this is possible within Xamarin forms itself. Can anyone help?
I should point out my data for the form is being retrieved asynchronously on a remote json endpoint
protected override void OnAppearing ()
{
base.OnAppearing ();
if (ViewModel == null || ViewModel.IsLoading)
return;
ViewModel.LoadItemsCommand.Execute (Club.ClubId);
}
My remote json api contains, Description contatins a HTML snippet which I would like to use.
{
ClubName: "Stourbridge",
Description: "<p>This club meets every TWO weeks on a <b>Friday</b>.</p>"
...
}
Try the following example that will show how to do the bindings.
Note that you have to use a HtmlWebViewSource to achieve this, and bind the WebView.Source to this.
Clicking the button will change the view model and update the WebView appropriately to the newly changed text.
StackLayout objStackLayout = new StackLayout();
MyView objMyView = new MyView();
objMyView.MyHtml = "<html><head></head><body><h1>Title</h1><p>Some body text</p></body></html>";
HtmlWebViewSource objHtmlWebViewSource = new HtmlWebViewSource();
objHtmlWebViewSource.SetBinding(HtmlWebViewSource.HtmlProperty, "MyHtml");
objHtmlWebViewSource.BindingContext = objMyView;
WebView objWebview = new WebView();
objWebview.HorizontalOptions = LayoutOptions.FillAndExpand;
objWebview.VerticalOptions = LayoutOptions.FillAndExpand;
objWebview.Source = objHtmlWebViewSource;
Button objMyButton2 = new Button();
objMyButton2.Text="Change Html";
objMyButton2.Clicked+=((o2,e2)=>
{
objMyView.MyHtml = "<html><head></head><body><h1>Title</h1><p>Some body text that has changed.</p></body></html>";
});
objStackLayout.Children.Add(objMyButton2);
objStackLayout.Children.Add(objWebview);
The view model is just a simple one with a bindable property as below:-
public class MyView
: Xamarin.Forms.View
{
public static readonly BindableProperty MyHtmlProperty = BindableProperty.Create<MyView, string>(p => p.MyHtml, default(string));
public string MyHtml
{
get { return (string)GetValue(MyHtmlProperty); }
set { SetValue(MyHtmlProperty, value); }
}
}
Before clicking the button gives:-
After clicking the button, adjusts the view model, and automatically updates the control via the binding giving:-

Set Adaptive Tile Background from Image

I am creating a TileNotification to display the last edited project on my app's tile. When doing this I want to set the tile's background to be the project cover image. I'm creating the TileContent like this:
TileContent content = new TileContent()
{
Visual = new TileVisual()
{
TileMedium = new TileBinding()
{
Content = new TileBindingContentAdaptive()
{
BackgroundImage = new TileBackgroundImage()
{
Source = new TileImageSource("ms-appx:///Assets/Images/MainPageBackground.jpg"),
Overlay = 10
},
Children =
{
new TileText()
{
Text = DataModel.Instance.CurrentProject.Title,
Align = TileTextAlign.Left
}
}
}
}
}
};
The problem is that the only way to set the Source property seems to be with a TileImageSource, which only accepts a string. And since the project's cover image is stored in ApplicationData.Current.LocalFolder... I can't just give it a string. Is there any way to set the image source from an actual image rather than a string?
After some more searching I found this method of doing it.
You can use the "ms-appdata:///Local" prefix to get the file. In my case:
$"ms-appdata:///local/Projects/{ProjectName}/Slides/0.gif".
That can then be handed in as the source.

Monotouch UICalendar Store Events In Custom DB

I'm using https://github.com/Clancey/UICalendar
I want to store the events that it adds as a row in my custom db table. However, I don't currently see that the UICalendar library actually exposes any events to do this. What is the best way to store events added using UICalendar into a custom db? Or at least get access to the event?
Any help extremely appreciated!
[EDIT]
Looks like I need to use EKEvent to find the currently saved value. How would I get the values from the event currently being triggered to save from my application?
Seems like UICalendar is only visual component. You should to handle store/load event via your own code. For example, via SQLite-net ORM library (http://code.google.com/p/sqlite-net/).
If you want to use UICalendar to show/edit event in systemt calendar, use EKEvent and other EventKit framework classes to reach that information.
I actually imported the UICalendar Project into my project and made the changes to CalendarViews.cs line 258 which is where this fun begins.
Below you can see exactly what I did to intercept the event so that they could associate some custom data that I need to store along with the event for the application. Basically this will intercept the event and present a DVC or DialogViewController to handle some extra user interaction. From here you can save stuff accordingly.
private void portriatNavBar ()
{
// _leftButton = new UIBarButtonItem("Calendars", UIBarButtonItemStyle.Bordered, HandlePreviousDayTouch);
NavigationItem.LeftBarButtonItem = _orgLefButton;
NavigationItem.Title = "Calendar";
_rightButton = new UIBarButtonItem (UIBarButtonSystemItem.Add, delegate {
addController = new EKEventEditViewController ();
// set the addController's event store to the current event store.
addController.EventStore = Util.MyEventStore;
addController.Event = EKEvent.FromStore(Util.MyEventStore);
addController.Event.StartDate = DateTime.Now;
addController.Event.EndDate = DateTime.Now.AddHours(1);
addController.Completed += delegate(object theSender, EKEventEditEventArgs eva) {
switch (eva.Action)
{
case EKEventEditViewAction.Canceled :
case EKEventEditViewAction.Deleted :
case EKEventEditViewAction.Saved:
this.NavigationController.DismissModalViewControllerAnimated(true);
break;
}
};
// Going to create a precursor to actually displaying the creation of a calendar event so we can grab everything correctly
RootElement _ctRoot = new RootElement ("Task Details") {
new Section () {
new RootElement ("Clients") {
AppSpecificNamespace.TaskController.GetClientsForCalendar ()
},
new RootElement ("Task Types") {
AppSpecificNamespace.TaskController.GetTypesForCalendar ()
}
},
new Section () {
new StyledStringElement ("Continue", delegate {
this.NavigationController.PopViewControllerAnimated (true);
this.NavigationController.PresentModalViewController (addController, true);
}) { Alignment = UITextAlignment.Center, TextColor = UIColor.Blue }
}
};
DialogViewController AppSpecificDVC = new DialogViewController (_ctRoot);
this.NavigationController.PushViewController (AppSpecificDVC, true);
//this.NavigationController.PresentViewController (AppSpecificDVC, true, null);
});
NavigationItem.RightBarButtonItem = _rightButton;
}
Hope this helps someone else.

moving a placemark in google earth using C#

I have been using Winform GEPlugin control example for my work.
http://code.google.com/p/winforms-geplugin-control-library/wiki/ExampleForm
my problem is i want to move my placemark (in C#, not KML), i tried a lot but it is not working.
kindly suggest me some solution for this. a sample of code will also be helpful.
I guess we can move it through java script and in winform-GE Plugin there are functions like injectJavascript and invokeJavascript, we can make use of those functions to execute javascript function..
Even I'm not able to move it exactly but I'm able to create a new placemark and delete the previous one which will give a sense that placemarks are moving.
<script
src="http://www.google.com/jsapi?key=ABQIAAAAuPsJpk3MBtDpJ4G8cqBnjRRaGTYH6UMl8mADNa0YKuWNNa8VNxQCzVBXTx2DYyXGsTOxpWhvIG7Djw"
type="text/javascript"></script>
<script type="text/javascript">
function addSampleButton(caption, clickHandler) {
var btn = document.createElement('input');
btn.type = 'button';
btn.value = caption;
if (btn.attachEvent)
btn.attachEvent('onclick', clickHandler);
else
btn.addEventListener('click', clickHandler, false);
// add the button to the Sample UI
document.getElementById('sample-ui').appendChild(btn);
}
function addSampleUIHtml(html) {
document.getElementById('sample-ui').innerHTML += html;
}
</script>
<script type="text/javascript">
var ge;
var placemark;
var counter = 0;
google.load("earth", "1");
function init() {
google.earth.createInstance('map3d', initCallback, failureCallback);
addSampleButton('Create a Placemark!', buttonClick);
addSampleButton('Remove last Placemark!', RemovebuttonClick);
}
function initCallback(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);
// Get the current view.
var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);
lookAt.setRange(1000);
// Set new latitude and longitude values.
lookAt.setLatitude(11.50);
lookAt.setLongitude(79.50);
// Update the view in Google Earth.
ge.getView().setAbstractView(lookAt);
createPlacemark();
document.getElementById('installed-plugin-version').innerHTML = ge
.getPluginVersion().toString();
}
function failureCallback(errorCode) {
}
function removePlacemark() {
//counter--;
// alert("placemark" + (counter -1));
ge.getFeatures().removeChild(placemark);
}
function createPlacemark() {
if (counter != 0)
removePlacemark();
placemark = ge.createPlacemark('');
placemark.setName("placemark" + counter);
ge.getFeatures().appendChild(placemark);
// Create style map for placemark
var icon = ge.createIcon('');
icon
.setHref('http://www.veryicon.com/icon/png/Transport/Transport%201/Car.png');
var style = ge.createStyle('');
style.getIconStyle().setIcon(icon);
placemark.setStyleSelector(style);
// Create point
var la = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);
var point = ge.createPoint('');
point.setLatitude(la.getLatitude());
point.setLongitude(la.getLongitude());
placemark.setGeometry(point);
placemark.
counter++;
}
function buttonClick() {
createPlacemark();
}
function RemovebuttonClick() {
removePlacemark();
}
</script>
You can try these script and if u r able to move by giving latitude and longitude, then please let me know

How to setup a Gtk# TreeModelFilter that filters an underlying TreeStore?

I have read the "GtkSharp TreeView tutorial" wherein the author describes how to setup and use a TreeModelFilter for an underlying ListStore ( under the tutorial section "Filtering Data"). The technique doesn't seem to work for an underlying hierarchical TreeStore. I want to filter a multilevel TreeStore and show the results in a TreeView. Its giving me a real hard time. Are there any tutorials, samples, or suggestions for doing it ?
Following is the code. Its basically the same code as the tutorial except for changes to deal with construction and population of a TreeStore rather than a ListStore.
{The TreeStore is used to save "names" and "email addresses" of contacts , divided into (and saved as) children of the roots "friends" and "relatives" }
// compilation requires references to:
// gtk-sharp, atk-sharp and glib-sharp
using System;
using Gtk;
public class TreeViewExample
{
public static void Main()
{
Gtk.Application.Init();
new TreeViewExample();
Gtk.Application.Run();
}
Gtk.Entry filterEntry;
Gtk.TreeModelFilter filter;
public TreeViewExample()
{
// Create a Window
Gtk.Window window = new Gtk.Window("TreeView Example");
window.SetSizeRequest(500, 200);
window.DeleteEvent += delegate { Application.Quit(); };
// Create an Entry used to filter the tree
filterEntry = new Gtk.Entry();
// Fire off an event when the text in the Entry changes
filterEntry.Changed += OnFilterEntryTextChanged;
// Create a nice label describing the Entry
Gtk.Label filterLabel = new Gtk.Label("Search:");
// Put them both into a little box so they show up side by side
Gtk.HBox filterBox = new Gtk.HBox();
filterBox.PackStart(filterLabel, false, false, 5);
filterBox.PackStart(filterEntry, true, true, 5);
// Create our TreeView
Gtk.TreeView tv = new Gtk.TreeView();
// Create a box to hold the Entry and Tree
Gtk.VBox box = new Gtk.VBox();
// Add the widgets to the box
box.PackStart(filterBox, false, false, 5);
box.PackStart(tv, true, true, 5);
window.Add(box);
//setting up columns and renderers
Gtk.TreeViewColumn nameColumn = new Gtk.TreeViewColumn { Title = "Name" };
Gtk.CellRendererText nameCell = new Gtk.CellRendererText();
nameColumn.PackStart(nameCell, true);
Gtk.TreeViewColumn emailColumn = new Gtk.TreeViewColumn { Title = "Email" };
Gtk.CellRendererText emailCell = new Gtk.CellRendererText();
emailColumn.PackStart(emailCell, true);
// Add the columns to the TreeView
tv.AppendColumn(nameColumn);
tv.AppendColumn(emailColumn);
// Tell the Cell Renderers which items in the model to display
nameColumn.AddAttribute(nameCell, "text", 0);
emailColumn.AddAttribute(emailCell, "text", 1);
// Create a model that will hold two strings
Gtk.TreeStore contacts = new Gtk.TreeStore(typeof(string), typeof(string));
// Add some hierarchical data
Gtk.TreeIter treeiter;
//first root
treeiter = contacts.AppendValues("FRIENDS");
// 2 children of first root
contacts.AppendValues(treeiter, "Ogre", "stinky#hotmale.com");
contacts.AppendValues(treeiter, "Bee", "stingy#coolguy.com");
// second root
treeiter = contacts.AppendValues("RELATIVES");
// 3 children of second root
contacts.AppendValues(treeiter, "Mommy", "mother#family.com");
contacts.AppendValues(treeiter, "Daddy", "father#family.com");
contacts.AppendValues(treeiter, "tom", "cousin#family.com");
filter = new Gtk.TreeModelFilter(contacts, null);
// Specify the function that determines which rows to filter out and which ones to display
filter.VisibleFunc = new Gtk.TreeModelFilterVisibleFunc(FilterTree);
// Assign the filter as our treeview's model
tv.Model = filter;
// Show the window and everything on it
window.ShowAll();
}
private void OnFilterEntryTextChanged(object o, System.EventArgs args)
{
// Since the filter text changed, tell the filter to re-determine which rows to display
filter.Refilter();
}
private bool FilterTree(Gtk.TreeModel model, Gtk.TreeIter iter)
{
string contactname = model.GetValue(iter, 0).ToString();
if (filterEntry.Text == "")
return true;
if (contactname.IndexOf(filterEntry.Text) > -1)
return true;
else
return false;
}
}
[I am using mono 2.6.4 /monodevelop 2.4 / gtk-sharp 2.12 on windows vista.]
It seems that when filtering rows in a tree model, a row is only visible if ALL its parents are visible too. Since your filter function hides the parent nodes, it will not display the child nodes even if the text matches. I have modified your code to illustrate this problem:
Now, one of the parent nodes begins with 'test'. If you type 'test' you'll see the filtering works correctly.
using System;
using Gtk;
public class TreeViewExample
{
public static void Main ()
{
Gtk.Application.Init ();
new TreeViewExample ();
Gtk.Application.Run ();
}
Gtk.Entry filterEntry;
Gtk.TreeModelFilter filter;
public TreeViewExample ()
{
// Create a Window
Gtk.Window window = new Gtk.Window ("TreeView Example");
window.SetSizeRequest (500,200);
window.DeleteEvent+=delegate {Application.Quit();};
// Create an Entry used to filter the tree
filterEntry = new Gtk.Entry ();
// Fire off an event when the text in the Entry changes
filterEntry.Changed += OnFilterEntryTextChanged;
// Create a nice label describing the Entry
Gtk.Label filterLabel = new Gtk.Label ("Search:");
// Put them both into a little box so they show up side by side
Gtk.HBox filterBox = new Gtk.HBox ();
filterBox.PackStart (filterLabel, false, false, 5);
filterBox.PackStart (filterEntry, true, true, 5);
// Create our TreeView
Gtk.TreeView tv = new Gtk.TreeView ();
// Create a box to hold the Entry and Tree
Gtk.VBox box = new Gtk.VBox ();
// Add the widgets to the box
box.PackStart (filterBox, false, false, 5);
box.PackStart (tv, true, true, 5);
window.Add (box);
//setting up columns and renderers
Gtk.TreeViewColumn nameColumn = new Gtk.TreeViewColumn{Title="Name"};
Gtk.CellRendererText nameCell = new Gtk.CellRendererText ();
nameColumn.PackStart (nameCell, true);
Gtk.TreeViewColumn emailColumn = new Gtk.TreeViewColumn {Title="Email"};
Gtk.CellRendererText emailCell = new Gtk.CellRendererText ();
emailColumn.PackStart (emailCell, true);
// Add the columns to the TreeView
tv.AppendColumn (nameColumn);
tv.AppendColumn (emailColumn);
// Tell the Cell Renderers which items in the model to display
nameColumn.AddAttribute (nameCell, "text", 0);
emailColumn.AddAttribute (emailCell, "text", 1);
// Create a model that will hold two strings
Gtk.TreeStore contacts = new Gtk.TreeStore (typeof (string), typeof (string));
// Add some hierarchical data
Gtk.TreeIter treeiter;
//first root
treeiter= contacts.AppendValues("testFRIENDS");
// 2 children of first root
contacts.AppendValues(treeiter, "testOgre", "stinky#hotmale.com");
contacts.AppendValues(treeiter, "testBee", "stingy#coolguy.com");
// second root
treeiter= contacts.AppendValues("RELATIVES");
// 3 children of second root
contacts.AppendValues (treeiter,"Mommy","mother#family.com");
contacts.AppendValues (treeiter,"Daddy", "father#family.com");
contacts.AppendValues (treeiter,"tom", "cousin#family.com");
filter = new Gtk.TreeModelFilter (contacts, null);
// Specify the function that determines which rows to filter out and which ones to display
filter.VisibleFunc = new Gtk.TreeModelFilterVisibleFunc (FilterTree);
// Assign the filter as our treeview's model
tv.Model = filter;
// Show the window and everything on it
window.ShowAll ();
}
private void OnFilterEntryTextChanged (object o, System.EventArgs args)
{
// Since the filter text changed, tell the filter to re-determine which rows to display
filter.Refilter ();
}
private bool FilterTree (Gtk.TreeModel model, Gtk.TreeIter iter)
{
string contactname = model.GetValue (iter, 0).ToString ();
if (filterEntry.Text == "")
return true;
if (contactname.IndexOf (filterEntry.Text) > -1)
return true;
else
return false;
}
}
The easiest solution with your current structure would be having the filter function always return TRUE for the 'container' nodes (Friends and Relatives), based upon a value in a hidden column in the model. It will not look exactly look the way you want, but it will work.
The GTK+ Treeview Tutorial, though not updated for some time,is still a VERY useful resource for all your TreeView needs. The code and examples are in C, but most of it still applies to GTK#.
In order to reach correct functionality of your code, I suggest you to modify it in following manner:
1.Add new field private filterBool = false; to your class
2.Modify your FilterTree method to this state:
private bool FilterTree (Gtk.TreeModel model, Gtk.TreeIter iter)
{
string contactname = model.GetValue (iter, 0).ToString ();
if (filterEntry.Text == "")
return true;
if (contactname.IndexOf (filterEntry.Text) > -1)
return true;
if (model.IterHasChild(iter))
{
filerBool = false;
investigateChildNodes(model, iter); //method checking if currently investigated
//node has any child fulfilling filter contitions
return filerBool;
}
return false;
}
3.Add missing method
private void investigateChildNodes(TreeModel model, TreeIter iter)
{
TreeIter childIter;
model.IterChildren(out childIter, iter);
do
{
if (model.GetValue(childIter, 0).ToString().IndexOf(filterEntry.Text) > -1)
filerBool = true;
if (model.IterHasChild(childIter))
investigateChildNodes(model, childIter);
} while (model.IterNext(ref childIter));
}
With this modification every node is checked for possible child nodes, which might fulfill filtering conditions. If any is detected, the node is not discarded.
Tinki version works flawlessly. The only thing which I do not like is the private variable. This can be eliminated by using a return value in the InvestigateChildrenNodes function.
private bool InvestigateChildNodes(TreeModel model, TreeIter iter)
{
TreeIter childIter;
model.IterChildren(out childIter, iter);
bool result = false;
do
{
if (model.GetValue(childIter, 0).ToString().Contains(FilterEntry.Text))
{
result = true;
break;
}
if (model.IterHasChild(childIter))
{
result = InvestigateChildNodes(model, childIter);
if (result)
break;
}
} while (model.IterNext(ref childIter));
return result;
}

Categories

Resources