I'm trying to show toast notifications in Win 10 from vb.net WPF app.
1. I added <TargetPlatformVersion>10.0</TargetPlatformVersion> to .vbproj file in the <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> section.
2. I Added references to Windows.Data and Windows.UI
3. My code:
Class MainWindow
Private Sub BtnClick()
Dim ToastN As ToastNotification = New ToastNotification("Test", "This is test notification.")
End Sub
End Class
Public Class ToastNotification
Public Sub New(Title As String, Message As String)
Dim TempStr As String = $"<toast>
<visual>
<binding template='ToastGeneric'>
<text>{Title}</text>
<text>{Message}</text>
</binding>
</visual>
</toast>"
Dim xmlDoc As Windows.Data.Xml.Dom.XmlDocument = New Windows.Data.Xml.Dom.XmlDocument()
xmlDoc.LoadXml(TempStr)
Dim Toast As Windows.UI.Notifications.ToastNotification = New Windows.UI.Notifications.ToastNotification(xmlDoc)
Windows.UI.Notifications.ToastNotificationManager.CreateToastNotifier(Title).Show(Toast)
End Sub
End Class
Button's click event is set to BtnClick
Application runs but doesn't do anything. Everything works fine just ...createTestNotifier(Title).Show(Toast) doesn't work.
Could you please help.
What am I doing wrong?
Source ZIP
You have to create a shortcut of your app
with that:
private bool TryCreateShortcut()
{
string shortcutPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + string.Format("\\Microsoft\\Windows\\Start Menu\\Programs\\{0}.lnk", Path.GetFileNameWithoutExtension(AppDomain.CurrentDomain.FriendlyName));
if (!File.Exists(shortcutPath))
{
InstallShortcut(shortcutPath);
return true;
}
return false;
}
private void InstallShortcut(string shortcutPath)
{
// Find the path to the current executable
string exePath = Process.GetCurrentProcess().MainModule.FileName;
IShellLinkW newShortcut = (IShellLinkW)new CShellLink();
// Create a shortcut to the exe
ErrorHelper.VerifySucceeded(newShortcut.SetPath(exePath));
ErrorHelper.VerifySucceeded(newShortcut.SetArguments(""));
// Open the shortcut property store, set the AppUserModelId property
IPropertyStore newShortcutProperties = (IPropertyStore)newShortcut;
using (PropVariant appId = new PropVariant(Utility.APP_ID))
{
ErrorHelper.VerifySucceeded(newShortcutProperties.SetValue(SystemProperties.System.AppUserModel.ID, appId));
ErrorHelper.VerifySucceeded(newShortcutProperties.Commit());
}
// Commit the shortcut to disk
IPersistFile newShortcutSave = (IPersistFile)newShortcut;
ErrorHelper.VerifySucceeded(newShortcutSave.Save(shortcutPath, true));
}
Related
As the image shown, the combo box text in my case is very long.
Without changing the width of the combo box, is there any method to show full text when the user hovers on it?
Without changing the width of the combo box, is there any method to show full text when the user hovers on it?
You can use the ToolTip component to show the items with long text when the mouse pointer hovers over the control. Whenever the SelectedIndex changes, measure the selected item by the TextRenderer.MeasureText method, and if the string's width is greater than the editbox's, set the long string as a tooltip for the control.
Note: The width of the EditBox = ComboBox.Width - ButtonWidth. You can get the ButtonWidth from the SystemInformation.VerticalScrollBarWidth property.
To apply this feature, let's create a little class and inherit the ComboBox control.
C#
// +
// using System.ComponentModel;
[DesignerCategory("Code")]
public class ComboBoxEx : ComboBox
{
private readonly ToolTip ttp;
public ComboBoxEx() : base() => ttp = new ToolTip();
private bool _showItemToolTip = true;
[DefaultValue(true)]
public bool ShowItemToolTip
{
get => _showItemToolTip;
set
{
if (_showItemToolTip != value)
{
_showItemToolTip = value;
ttp.SetToolTip(this, string.Empty);
}
}
}
protected override void OnSelectedIndexChanged(EventArgs e)
{
base.OnSelectedIndexChanged(e);
if (ShowItemToolTip)
{
string str = string.Empty;
if (SelectedIndex >= 0)
{
var sz = TextRenderer.MeasureText(Text, Font);
if (sz.Width > Width - SystemInformation.VerticalScrollBarWidth)
str = Text;
}
ttp.SetToolTip(this, str);
}
}
protected override void Dispose(bool disposing)
{
if (disposing) ttp.Dispose();
base.Dispose(disposing);
}
}
VB.Net
' +
' Imports System.ComponentModel
<DesignerCategory("Code")>
Public Class ComboBoxEx
Inherits ComboBox
Private ReadOnly ttp As ToolTip
Sub New()
MyBase.New
ttp = New ToolTip()
End Sub
Private _showItemToolTip As Boolean = True
<DefaultValue(True)>
Public Property ShowItemToolTip As Boolean
Get
Return _showItemToolTip
End Get
Set(value As Boolean)
If (_showItemToolTip <> value) Then
_showItemToolTip = value
ttp.SetToolTip(Me, String.Empty)
End If
End Set
End Property
Protected Overrides Sub OnSelectedIndexChanged(e As EventArgs)
MyBase.OnSelectedIndexChanged(e)
If ShowItemToolTip Then
Dim str = ""
If SelectedIndex >= 0 Then
Dim sz = TextRenderer.MeasureText(Text, Font)
If sz.Width > Width - SystemInformation.VerticalScrollBarWidth Then
str = Text
End If
End If
ttp.SetToolTip(Me, str)
End If
End Sub
Protected Overrides Sub Dispose(disposing As Boolean)
If disposing Then ttp.Dispose()
MyBase.Dispose(disposing)
End Sub
End Class
You can use the same approach if you don't want to subclass. Drop a ToolTip component and handle the ComboBox.SelectedIndexChanged event as shown above.
I have Live Chart that I am trying to perform a fresh of the values on Button_Click event but the Chart is not refreshing.
I have two TextBoxes where the user can select the start and end date they would like to review and use the butn_ExecuteQuery_Click to display the data.
public HBDBreakdown()
{
InitializeComponent();
ChartValues();
}
private void ChartValues()
{
try
{
// Defines the variable for differnt lines.
List<double> SmallCommercialIndustValues = new List<double>();
List<double> ResidentialValues = new List<double>();
List<string> AnalystName = new List<string>();
SqlConnection connection = new SqlConnection("Data Source=WINDOWS-B1AT5HC\\MSSQLSERVER2;Initial Catalog=CustomerRelations;user id=sa; password=Westside2$; Integrated Security=False;");
string selectQuery = ("SELECT Users.TX_EMPLOYEE, SUM(CASE WHEN d .REV_CLS <> 2 THEN 1 ELSE 0 END) AS Residential, SUM(CASE WHEN d .REV_CLS = 2 THEN 1 ELSE 0 END) AS SmallCommercialIndust FROM hb_Disputes AS d INNER JOIN Users ON d.ASSGNTO = Users.KY_USER_ID WHERE(d.OPENED >=#OPENED) AND(d.OPENED < #CLOSED) GROUP BY Users.TX_EMPLOYEE; ");
connection.Open();
SqlCommand command = new SqlCommand(selectQuery, connection);
command.Parameters.Add("#OPENED", SqlDbType.DateTime).Value = dtepicker_Open.Text;
command.Parameters.Add("#CLOSED", SqlDbType.DateTime).Value = dtepicker_DateResolved.Text;
SqlDataReader sqlReader = command.ExecuteReader();
while (sqlReader.Read())
{
// Check for DBNull and then assign the variable
if (sqlReader["SmallCommercialIndust"] != DBNull.Value)
SmallCommercialIndustValues.Add(Convert.ToInt32(sqlReader["SmallCommercialIndust"]));
// Check for DBNull and then assign the variable
if (sqlReader["Residential"] != DBNull.Value)
ResidentialValues.Add(Convert.ToInt32(sqlReader["Residential"]));
// Check for DBNull and then assign the variable
AnalystName.Add(Convert.ToString(sqlReader["TX_EMPLOYEE"]));
}
SeriesCollection = new SeriesCollection
{
new StackedColumnSeries
{
Title = "Residential",
Values = new ChartValues<double>(ResidentialValues),
StackMode = StackMode.Values, // this is not necessary, values is the default stack mode
DataLabels = true
},
new StackedColumnSeries
{
Title = "Small Commercial Indust",
Values = new ChartValues<double>(SmallCommercialIndustValues),
StackMode = StackMode.Values,
DataLabels = true
}
};
Labels = AnalystName.ToArray();
//Formatter = value => value + " Disputes";
DataContext = this;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public SeriesCollection SeriesCollection { get; set; }
public string[] Labels { get; set; }
public Func<double, string> Formatter { get; set; }
private void butn_ExecuteQuery_Click(object sender, RoutedEventArgs e)
{
// Refresh Chart
ChartValues();
}
Set DataContext = null; before you call ChartValues() or implement INotifyPropertyChanged and raise the PropertyChanged event from the setters of the source properties.
Better never reset the DataContext only to update the data binding of certain properties. This results in very bad performance as the complete view will be forced to render again. The DataContext is also inherited down the element tree.
Better write cleaner code and handle dynamic data more gracefully and as intended by the framework (see Data Binding Overview).
Inside a control (or on a DependencyObject in general) you should always implement all properties that are involved in data binding as DependencyProperty.
They will automatically refresh the target and depending on the Binding.Mode also the source of the specific Binding.
Since you are reassigning SeriesCollection and Labels, both properties should be a DependencyProperty.
In your case, you can go without implementing dependency properties, because you are only updating collections. So simply avoid reassigning a new collection on each refresh and instead use IList.Clear and IList.Add on collections that implement INotifyCollectionChanged.
SeriesCollection already implements INotifyCollectionChanged, so you only need to change the type of the Labels property from string[] to ObservableCollection<string>. This way IList.Clear and IList.Add operations will be automatically reflected by the binding target (the chart control):
public SeriesCollection SeriesCollection { get; set; }
public ObservableCollection<string> Labels { get; set; }
public HBDBreakdown()
{
InitializeComponent();
// Set the `DataContext` once in the constructor
this.DataContext = this;
// Initialize the collection to prepare them for dynamic clear/add
this.SeriesCollection = new SeriesCollection();
this.Labels = new ObservableCollection<string>();
}
private void ChartValues()
{
try
{
...
this.SeriesCollection.Clear();
this.SeriesCollection.Add(
new StackedColumnSeries
{
Title = "Residential",
Values = new ChartValues<double>(ResidentialValues),
StackMode = StackMode.Values, // this is not necessary, values is the default stack mode
DataLabels = true
});
this.SeriesCollection.Add(
new StackedColumnSeries
{
Title = "Small Commercial Indust",
Values = new ChartValues<double>(SmallCommercialIndustValues),
StackMode = StackMode.Values,
DataLabels = true
});
this.Labels.Clear();
AnalystName.ForEach(this.Labels.Add);
}
// Code smell: never catch 'Exception'.
// Only catch explicitly those exception you can handle.
// A user can't handle exceptions, so in a real business application you wouldn't show the exception message to the user.
catch (Exception ex)
{
// Bad practice
MessageBox.Show(ex.Message);
}
}
Please also read: Exceptions and Exception Handling, especially Exceptions Overview and Design Guidelines for Exceptions.
I'm trying to using MVVM binding for the pdfviewer but the document always turns out blank. I'm querying a DB field that contains the bytes of the PDF file and I'm trying to get it to display in the viewer (I've confirmed that the file is not malformed and it displays fine if I save it as a PDF to my desktop).
Here are my MVVM properties:
private RadFixedDocument _currentDocument;
public RadFixedDocument CurrentDocument
{
get => _currentDocument; set => this.RaiseAndSetIfChanged(ref _currentDocument, value);
}
Here is the method I'm using to populate the CurrentDocument property:
var sqlStr = #"select top 1 * from FileManager order by ID desc;";
var file = await con.QuerySingleAsync<FMFile>(sqlStr);
var fileBytes = file.FileContent.ToArray(); // this is type byte[] - I confirmed that it has the correct contents
var ms = new MemoryStream(fileBytes); // ms gets filled properly
FormatProviderSettings settings = new FormatProviderSettings(ReadingMode.AllAtOnce);
PdfFormatProvider provider = new PdfFormatProvider(ms, settings);
CurrentDocument = provider.Import();
And here is how my XAML looks:
<telerik:RadPdfViewerToolBar RadPdfViewer="{Binding ElementName=pdfViewer, Mode=OneTime}" />
<telerik:RadPdfViewer x:Name="pdfViewer"
Grid.Row="1"
DocumentSource="{Binding CurrentDocument, Mode=TwoWay}" />
However, nothing get's displayed in the viewer. I confirmed that my VM is hooked up correctly as other property display just fine. Any advice would be appreciated.
So it looks like you are binding to the wrong Object Type.
Instead of a RadFixedDocument, Bind to type PdfDocumentSource.
private PdfDocumentSource _PDFDocument;
public PdfDocumentSource PDFDocument
{
get { return _PDFDocument; }
set
{
_PDFDocument = value;
OnPropertyChanged("PDFDocument");
}
}
private void LoadPDFDocument(string pdfFilePath)
{
MemoryStream stream = new MemoryStream();
using (Stream input = File.OpenRead(pdfFilePath))
{
input.CopyTo(stream);
}
FormatProviderSettings settings = new FormatProviderSettings(ReadingMode.OnDemand);
PDFDocument = new PdfDocumentSource(stream, settings);
}
Just discovered what is causing a HTML editor to throw the toys out when using a certain letter on a keyboard...
On the same page there are textboxes that contain things like html page name, title, navigate URL, menu text.... If one of the textboxes contains text with an underscore (say 'Test_Page') then the letter 'P' will not function in the HTML editor. I'm guessing (and could be way off base here as I didn't think textbox.txt could do this unlike Label.content) that WPF is taking the text entry and using it as a mnemonic key.. I do know that setting RecognisesAccessKey to false might cure it, but can't find a way to add that property or access ContentPresenter...
This is the class that I use to create the control and ideally would like to set it here
Public Class TBx
Inherits TextBox
Public Shared IsNewRecordProperty As DependencyProperty = DependencyProperty.Register("IsNewRecord", GetType(Boolean), GetType(TBx), New PropertyMetadata(New PropertyChangedCallback(AddressOf IsNewRecordChanged)))
Public Property IsNewRecord As Boolean
Get
Return GetValue(IsNewRecordProperty)
End Get
Set(value As Boolean)
SetValue(IsNewRecordProperty, value)
End Set
End Property
Protected Overrides Sub OnInitialized(e As System.EventArgs)
MyBase.OnInitialized(e)
VerticalAlignment = Windows.VerticalAlignment.Center
HorizontalAlignment = Windows.HorizontalAlignment.Left
BorderBrush = New SolidColorBrush(Colors.Silver)
Height = 22
SpellCheck.IsEnabled = True
UndoLimit = 0
If IsNewRecord = True Then
BorderThickness = New Thickness(1)
IsReadOnly = False
Background = New SolidColorBrush(Colors.White)
Else
BorderThickness = New Thickness(0)
IsReadOnly = True
Background = New SolidColorBrush(Colors.Transparent)
End If
End Sub
Private Shared Sub IsNewRecordChanged(sender As DependencyObject, e As DependencyPropertyChangedEventArgs)
Dim vControl As TBx = TryCast(sender, TBx)
Dim vBoolean As Boolean = e.NewValue
If vBoolean = True Then
vControl.BorderThickness = New Thickness(1)
vControl.IsReadOnly = False
vControl.Background = New SolidColorBrush(Colors.White)
Else
vControl.BorderThickness = New Thickness(0)
vControl.IsReadOnly = True
vControl.Background = New SolidColorBrush(Colors.Transparent)
End If
End Sub
End Class
Thank you
Couldn't find an easy way to do this from the class, but this works on the page
Dim CP As New ContentPresenter
CP.RecognizesAccessKey = False
Then add the TextBox to the ContentPresenter
Case 1
vLabel.Text = "Page Name"
With vTB
.Width = 200
.Name = vName & "PageNameTB"
.ToolTip = "This is the short name for the page"
.IsNewRecord = IsNewRecord
End With
CP.Content = vTB
The add the CP to the grid
RegisterControl(SecurePage_Grid, vTB)
Grid.SetColumn(vLabel, 0)
Grid.SetRow(vLabel, i)
If i = 1 Then
Grid.SetRow(CP, i)
Grid.SetColumn(CP, 1)
Else
Grid.SetRow(vTB, i)
Grid.SetColumn(vTB, 1)
End If
vGrid.Children.Add(vLabel)
If i = 1 Then
vGrid.Children.Add(CP)
Else
vGrid.Children.Add(vTB)
End If
Are there any samples for setting up Winforms (or WPF) that use the Google Earth API? I see a lot of deprecated stuff (FC.GEPlugins). I know that I need a webbrowser control, but I am not sure how to even assign this to the plugin.
Would love a simple application that shows how to pass a latitude/longitude to the plugin and put a marker on the location.
Thanks!
you can achieve that by building a KML file form your code and run it ,its quit simple.
Here an C# code example :
StreamWriter _writer = new StreamWriter("C:\Map.KML");
_writer.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?><kml xmlns=\"http://www.opengis.net/kml/2.2\">");
_writer.WriteLine("<Document>");
_writer.WriteLine("<Placemark>");
_writer.WriteLine("<Style>");
_writer.WriteLine("<IconStyle>");
_writer.WriteLine("<color>ccaa00ee</color>");
_writer.WriteLine("</IconStyle>");
_writer.WriteLine("<LabelStyle>");
_writer.WriteLine("<color>ccaa00ee</color>");
_writer.WriteLine("</LabelStyle>");
_writer.WriteLine("</Style>");
_writer.WriteLine("<name>");
_writer.WriteLine(your location name);
_writer.WriteLine("</name>");
_writer.WriteLine("<Point>");
_writer.WriteLine("<coordinates>" + your longitude + "," + your latitude + "</coordinates>");
_writer.WriteLine("</Point>");
_writer.WriteLine("</Placemark>");
}
_writer.WriteLine("</Document>");
_writer.WriteLine("</kml>");
_writer.Close();
System.Diagnostics.Process.Start("C:\Map.KML");
after I posted this I realized you asked for google earth not google maps - this is an example of google maps. hopefully it can help some
create a form
'Using the control
Public Class Mapping
Dim wide As Integer
Dim high As Integer
Private GoogleControl1 As GoogleControl
Sub New()
' This call is required by the Windows Form Designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
GoogleControl1 = New GoogleControl() With {.Dock = DockStyle.Fill}
Me.Controls.Add(GoogleControl1)
End Sub
End class
create a class
'The Control
'The class needs to be marked as com visible so the
'script in the GoogleMap.htm can call some of the subs.
<System.Runtime.InteropServices.ComVisibleAttribute(True)> _
Public Class GoogleControl : Inherits UserControl
Dim cnn As New MySqlConnection()
Dim cmd As New MySqlCommand
Dim adptr As New MySqlDataAdapter
Dim current As String
Dim filltab As New DataTable
Dim pop As Integer
Private WebBrowser1 As WebBrowser
Private StatusStrip1 As StatusStrip
Private StatusButtonDelete As ToolStripButton
Private StatusLabelLatLng As ToolStripStatusLabel
Private lastupdated As ToolStripStatusLabel
Private InitialZoom As Integer
Private timer2 As Timer
Private InitialLatitude As Double
Private InitialLongitude As Double
Private components As System.ComponentModel.IContainer
Private InitialMapType As GoogleMapType
Dim mapcontains As New System.Collections.Generic.HashSet(Of String)
'I use this enum to store the current map
'type into the application's settings.
'So when the user closes the map on Satellite
'mode it will be on Satellite mode the next
'time they open it.
Public Enum GoogleMapType
None
RoadMap
Terrain
Hybrid
Satellite
End Enum
Sub New()
MyBase.New()
WebBrowser1 = New WebBrowser
StatusStrip1 = New StatusStrip
StatusButtonDelete = New ToolStripButton
StatusLabelLatLng = New ToolStripStatusLabel
lastupdated = New ToolStripStatusLabel
WebBrowser1.Dock = DockStyle.Fill
timer2 = New Timer() With {.Interval = 10000, .Enabled = True}
WebBrowser1.AllowWebBrowserDrop = False
WebBrowser1.IsWebBrowserContextMenuEnabled = False
WebBrowser1.WebBrowserShortcutsEnabled = False
WebBrowser1.ObjectForScripting = Me
WebBrowser1.ScriptErrorsSuppressed = True
AddHandler WebBrowser1.DocumentCompleted, AddressOf WebBrowser1_DocumentCompleted
StatusStrip1.Dock = DockStyle.Bottom
' StatusStrip1.Items.Add(StatusButtonDelete)
' StatusStrip1.Items.Add(StatusLabelLatLng)
StatusStrip1.Items.Add(lastupdated)
StatusButtonDelete.Text = "Delete Markers"
' AddHandler StatusButtonDelete.Click, AddressOf StatusButtonDelete_Click
AddHandler timer2.Tick, AddressOf Timer2_Tick
Me.Controls.Add(WebBrowser1)
Me.Controls.Add(StatusStrip1)
'The default map settings.
InitialZoom = 10
InitialLatitude = 36.8438126
InitialLongitude = -76.2862457
InitialMapType = GoogleMapType.RoadMap
End Sub
Sub New(ByVal zoom As Integer, ByVal lat As Double, ByVal lng As Double, ByVal mapType As GoogleMapType)
'This constructor could be used to start the map with different values
'other than the default settings.
Me.New()
InitialZoom = zoom
InitialLatitude = lat
InitialLongitude = lng
InitialMapType = mapType
End Sub
Private Sub GoogleControl_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Load the htm doc into the webrowser.
'When it completes, intialize the map.
WebBrowser1.DocumentText = My.Computer.FileSystem.ReadAllText("GoogleMap.htm")
End Sub
Private Sub WebBrowser1_DocumentCompleted(ByVal sender As Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs)
'Initialize the google map with the initial settings.
'The Initialize script function takes four parameters.
'zoom, lat, lng, maptype. Call the script passing the
'parameters in.
WebBrowser1.Document.InvokeScript("Initialize", New Object() {InitialZoom, InitialLatitude, InitialLongitude, CInt(InitialMapType)})
End Sub
Public Sub Map_MouseMove(ByVal lat As Double, ByVal lng As Double)
'Called from the GoogleMap.htm script when ever the mouse is moved.
StatusLabelLatLng.Text = "lat/lng: " & CStr(Math.Round(lat, 4)) & " , " & CStr(Math.Round(lng, 4))
End Sub
Public Sub Map_Click(ByVal lat As Double, ByVal lng As Double)
'Add a marker to the map.
' Dim MarkerName As String = InputBox("Enter a Marker Name", "New Marker")
' If Not String.IsNullOrEmpty(MarkerName) Then
'The script function AddMarker takes three parameters
'name,lat,lng. Call the script passing the parameters in.
' WebBrowser1.Document.InvokeScript("AddMarker", New Object() {MarkerName, lat, lng})
' End If
End Sub
Public Sub Map_Idle()
'Would be a good place to load your own custom markers
'from data source
End Sub
' Private Sub StatusButtonDelete_Click(ByVal sender As Object, ByVal e As EventArgs)
'Call the DeleteMarkers script in the htm doc.
' WebBrowser1.Document.InvokeScript("DeleteMarkers")
' End Sub
Private Sub InitializeComponent()
Me.SuspendLayout()
'
'GoogleControl
'
Me.Name = "GoogleControl"
Me.ResumeLayout(False)
End Sub
End Class
then create a html file called GoogleMap.htm
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html {
height: 100%;
}
body {
height: 100%;
margin: 0;
padding: 0;
}
#map_canvas {
height: 100%;
}
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"> </script>
<script type="text/javascript">
var map;
var Markers = [];
function Initialize(zoomLevel, lat, lng, type) {
//Get the type of map to start.
//Need to convert the GoogleMapType enum
//to an actual Google Map Type
var MapType;
switch (type) {
case 1:
MapType = google.maps.MapTypeId.ROADMAP;
break;
case 2:
MapType = google.maps.MapTypeId.TERRAIN;
break;
case 3:
MapType = google.maps.MapTypeId.HYBRID;
break;
case 4:
MapType = google.maps.MapTypeId.SATELLITE;
break;
default:
MapType = google.maps.MapTypeId.ROADMAP;
};
//Create an instance of the map with the lat, lng, zoom, and
//type passed in
var myLatlng = new google.maps.LatLng(lat, lng);
var myOptions = { zoom: zoomLevel, center: myLatlng, mapTypeId: MapType };
var MarkerSize = new google.maps.Size(48, 48);
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
google.maps.event.addListener(map, 'click', Map_Click);
google.maps.event.addListener(map, 'mousemove', Map_MouseMove);
google.maps.event.addListener(map, 'idle', Map_Idle);
}
function Map_Click(e) {
window.external.Map_Click(e.latLng.lat(), e.latLng.lng());
}
function Map_MouseMove(e) {
window.external.Map_MouseMove(e.latLng.lat(), e.latLng.lng());
}
function Map_Idle() {
window.external.Map_Idle();
}
function DeleteMarkers() {
if (Markers) {
for (i in Markers) {
Markers[i].setMap(null);
google.maps.event.clearInstanceListeners(Markers[i]);
Markers[i] = null;
}
Markers.length = 0;
}
}
function AddMarker(name, lat, lng) {
var MarkerLatLng = new google.maps.LatLng(lat, lng);
var MarkerOption = { map: map, position: MarkerLatLng, title: name };
var Marker = new google.maps.Marker(MarkerOption);
Markers.push(Marker);
MarkerLatLng = null;
MarkerOption = null;
}
</script>
</head>
<body>
<div id="map_canvas" style="width: 100%; height: 100%">
</div>
</body>
</html>
congratulations you are in business - load the form and you should have a map looking at the center of the Hampton Roads, VA area. to change the location go to
InitialZoom = 10
InitialLatitude = 36.8438126
InitialLongitude = -76.2862457
the higher the zoom number the closer you will be to streetview
initial lat and long must be in decimal
to add a marker you would use vb.net
WebBrowser1.Document.InvokeScript("AddMarker", New Object() {"Description entered here", lat, long})
you could easily add 2 textboxes and a button and run this script with the lat and long from the textboxes
good luck
Why do you say deprecated? You can use the FC.GEPluginCtrls.GEWebBrowser in both winforms and WPF - it inherits from the standard webbrowser control and can be used wherever that can.
To load the plugin, add a marker and fly to the location you would simply do.
namespace ExampleFormTest
{
using System;
using System.Windows.Forms;
using FC.GEPluginCtrls;
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
geWebBrowser1.LoadEmbededPlugin();
// Handle the he PluginReady event
geWebBrowser1.PluginReady += (o, e) =>
{
// Here you can now use 'ge' exactly as you would
// in the native javascript api.
dynamic ge = e.ApiObject;
// create a placemark at (52, -2) look at it
var placemark = KmlHelpers.CreatePlacemark(ge, 'myPm', 52, -2);
GEHelpers.FlyToObject(ge, placemark);
};
}
}
}
There is an example of setting up the controls here.