-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathForm1.cs
102 lines (82 loc) · 3.09 KB
/
Form1.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
using CefSharp;
using CefSharp.WinForms;
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using System.Text.Json;
using GeocodingClient.Api;
using GeocodingClient.Model;
namespace CefMap
{
public partial class Form1 : Form
{
private static readonly string apiKey = ""; // Get your free api key at https://developer.myptv.com/
private static LocationsApi locationsApi;
public Form1()
{
InitializeComponent();
InitializeChromium();
if (string.IsNullOrEmpty(apiKey))
MessageBox.Show("You need an api key! Get your free key at https://developer.myptv.com/");
locationsApi = new LocationsApi(new GeocodingClient.Client.Configuration
{
ApiKey = new Dictionary<string, string>
{
["apiKey"] = apiKey
}
});
}
private ChromiumWebBrowser browser;
public void InitializeChromium()
{
// Create a browser component
browser = new ChromiumWebBrowser(Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase,
$"Map.html?apiKey={apiKey}"));
// Add it to the form and fill it to the container panel.
this.mapPanel.Controls.Add(browser);
browser.Dock = DockStyle.Fill;
browser.JavascriptMessageReceived += OnReceiveNotification;
}
private void button1_Click(object sender, EventArgs e)
{
var result = locationsApi.SearchLocationsByText(textBox1.Text);
SetLocations(result.Locations);
}
private void OnReceiveNotification(object sender, JavascriptMessageReceivedEventArgs e)
{
if (e == null)
return;
dynamic message = e.Message;
switch (message.Event)
{
case "click":
// need to wrap longitude (outside -180/+180)
var result = locationsApi.SearchLocationsByPosition(message.Lat, (message.Lng % 360 + 540) % 360 - 180);
// have to invoke it on the WinForms thread
if(InvokeRequired)
Invoke(new Action(() => SetLocations(result.Locations)));
break;
}
}
private void SetLocations(List<Location> locations)
{
dataGridView1.DataSource = locations;
// browser.ShowDevTools();
browser.GetMainFrame().ExecuteJavaScriptAsync(FormattableString.Invariant(
$@"setLocations('{JsonSerializer.Serialize(locations)}')"));
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Return)
{
button1_Click(sender, null);
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
browser.Dispose();
Cef.Shutdown();
}
}
}