Creating a .Net desktop application that utilizes the WebBrowser control and integrates with the Google Maps

I am currently working on a project that involves allowing users to input an address and then click a button. The entered address will be displayed on the WebBrowser control in a .net windows application. I am aware that JavaScript can be executed on the WebBrowser using WebBrowser1.DocumentText, followed by calling the script with WebBrowser1.Document.InvokeScript...

While I have encountered some challenges with this process, I am hopeful that someone here can guide me in the right direction.

CODE:

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

  Dim AddressMap As String

  AddressMap = AddressM.Text

  WebBrowser1.DocumentText = "<html><head><meta name='viewport' content='initial-scale=1.0, user-scalable=no' />" & _
    "<script type='text/javascript' src='http://maps.google.com.mx/maps/api/js?sensor=true&language;=es'></script>" & _
    "<script type='text/javascript'>" & _
    "var geocoder; var map;" & _
    "function initialize() " & _
    "{geocoder = new google.maps.Geocoder(); var myOptions = { zoom: 16, mapTypeId: google.maps.MapTypeId.ROADMAP()" & _
    "} var(address = " & AddressMap & ")" & _
    "geocoder.geocode({ 'address': address }, function (results, status) {" & _
                    "if (status == google.maps.GeocoderStatus.OK) {" & _
                        "map.setCenter(results[0].geometry.location);" & _
                        "var marker = new google.maps.Marker({" & _
                           " map: map," & _
                            "position: results[0].geometry.location });" & _
                    "} else {" & _
                    "}});" & _
     "map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);}" & _
     "</script></head><div id='map_canvas' style='width:100%; height:100%'></div></body></html>"

   WebBrowser1.Document.InvokeScript("Initialize")

End Sub

Here is another code snippet which I believe should work, but it still triggers a script error "An error has occurred in the script on this page" Line 1 Char 124 Error Expected ';' Code 0 URL about.blank

 WebBrowser1.DocumentText = "<html><head><script type='text/javascript' src='http://maps.google.com.mx/maps/api/js?sensor=false&language;=es'></script> " +
                           "<script type='text/javascript'> " +
                           "var geocoder; " +
                           "var map; " +
                           "function initialize(address) { " +
                           "geocoder = new google.maps.Geocoder(); " +
                           "var myOptions = { zoom: 16 } " +
                           "geocoder.geocode({ 'address': address }, function (results, status) { map.setCenter(results[0].geometry.location); " +
                           "var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location }); " +
                           "map = new google.maps.Map(document.getElementById('map_canvas'), myOptions); " +
                           "} " +
                           "</script> " +
                           "</head> " +
                           "<body> <div id='map_canvas' style='width:100%; height:100%'></div> </body> </html>"

WebBrowser1.Document.InvokeScript("initialize", New String() {AddressM.Text})

Appreciate any assistance provided.

Leo P.

This final piece of code is slightly different from the previous two and contains an if-else statement extracted from HTML that executes the Google Maps script.

WebBrowser1.DocumentText = "<html><head><script type='text/javascript' src='http://maps.google.com.mx/maps/api/js?sensor=false&language;=es'></script> " +
                       "<script type='text/javascript'> " +
                       "var geocoder; " +
                       "var map; " +
                       "function initialize() { " +
                       "geocoder = new google.maps.Geocoder(); " +
                       "var myOptions = { zoom: 16, mapTypeId: google.maps.MapTypeId.ROADMAP } " +
                       "var(address = 'Miami Beach, Florida') " +
                       "geocoder.geocode({ 'address': address }, " +
                       "function (results, status) { " +
                       "if (status == google.maps.GeocoderStatus.OK) { map.setCenter(results[0].geometry.location); " +
                       "var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location }); " +
                       "} else { alert('Geocode was not successful !);}}); " +
                       "map = new google.maps.Map(document.getElementById('map_canvas'), myOptions); } " +
                       "</script> " +
                       "</head> " +
                       "<body> <div id='map_canvas' style='width:100%; height:100%'></div> </body> </html>"

        WebBrowser1.Document.InvokeScript("initialize")

Shown below is the HTML code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />

<script type="text/javascript" src="http://maps.google.com.mx/maps/api/js?sensor=true&language=es"></script>
... (remaining HTML code)...

Answer №1

Solution Implementation

HTML Instructions

To create an HTML page, save it in C:\page.html and use the following code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />

<script type="text/javascript" src="http://maps.google.com.mx/maps/api/js?sensor=true&language=es"></script>
<script type="text/javascript">

    var geocoder;
    var map;


    function initialize(address) {

        geocoder = new google.maps.Geocoder();

        var myOptions = {
            zoom: 16,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }

        geocoder.geocode({ 'address': (address ? address : "Miami Beach, Flordia")}, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                var marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location
                });
            } else {
                alert("Geocode was not successful for the following reason: " + status);
            }
        });

        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    }


    </script>
  </head>
  <body onload="initialize()">
    <div id="map_canvas" style="width:100%; height:100%"></div>

  </body>
</html>

Windows Form - C# Introduction

private void Form1_Load(object sender, EventArgs e)
{
    // Enter the URL (e.g. http://www.example.com/page.html or c:\page.html)
    webBrowser1.Url = new Uri(@"C:\page.html");
}

private void button1_Click(object sender, EventArgs e)
{
    webBrowser1.Document.InvokeScript("initialize", 
            new string[] { textBox1.Text });
}

You will need a form with these components named as follows: textBox1, button1, and webBrowser1.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating functions within the $scope that do not directly access the $scope object

tag, I am looking to create a $scope function that specifically manipulates the variables it receives. To test this functionality, I have set up a Plunker available at http://plnkr.co/edit/BCo9aH?p=preview. In my setup, there is an ng-repeat loop that lis ...

How can you prevent multiple instances of JavaScript objects from being disposed of after they have completed their task?

I'm facing an issue with the code snippet below: $(document).ready(function() { $('.container').ready(function() { var v = new Video($(this)); v.load(); }); }); I'm trying to prevent the object 'v&apos ...

Turning On/Off Input According to Selection (Using jQuery)

<select name="region" class="selection" id="region"> <option value="choice">Choice</option> <option value="another">Another</option> </select> <input type="text" name="territory" class="textfield" id="territo ...

How to use PHP and JavaScript to update a location marker on Google Maps

I'm new to web development and in need of some help, please. I have a code that is supposed to update the marker location with coordinates retrieved from a database. <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AP ...

Adding a JSON object to an API call: step-by-step guide

I have a variety of Objects stored in an array that are generated dynamically. My goal is to save each Object separately by sending it through an API. The challenge lies in the fact that there can be numerous Objects in the array. What would be the most ef ...

Tips for resolving the issue of "Warning: validateDOMNesting(...): <div> cannot be a child of <tbody>"

Users list is passed as a prop to the UserItem Component in order to iterate over the user list and display them on a table. The list is being displayed correctly, and there are no divs in the render return, but an error persists: tried many solutions fou ...

What is causing the turn.js demo to not function properly?

I tested the demo script on fiddle as recommended in the official docs. Upon downloading the script and trying to run it in my browser, I encountered a problem where it did not work, and no errors were displayed on the console. Curiously, when I ran the ...

Problem with repetitive looping of Jquery click event within an Angular controller

Currently, I am in the process of creating an app using onsen UI (angular based) + phonegap. One issue I am facing is related to a JQuery click event inside an angular controller. The problem arises when I navigate back through the page stack and then ret ...

`Unable to retrieve Shopify products using shopify-api-node`

I'm encountering a 403 error while trying to retrieve products from my custom Shopify app using the shopify-api-node module. Below is the code snippet I've put together based on a helpful discussion on Stackoverflow: const express = require(& ...

Utilizing Drop-down Menus with Check-boxes in ASP.NET

I am facing an issue with my 2 drop-down boxes where I want the first drop-down to filter the second one in a cascading manner. The first drop-down contains checkboxes and I am trying to pass the selected items from the first drop-down to the second one, b ...

Mobile compatibility in ECMAScript 5.1 is essential for creating seamless user

Is there a reliable source for information on ECMAScript 5.1 compatibility with mobile browser devices? ...

Learning to extract data with multiple parameters in Node.js

I am struggling to retrieve data that meets both parameter conditions. I want the data to be filtered by status and display search results, but currently it is showing all records without considering the status value: const customers = await Customer.fi ...

Load an external URL and load a file from the local directory using Electron

For an upcoming art exhibition, I have a video installation that consists of large videos (several GBs) and an online hosted web application. To conserve bandwidth during the exhibition, I am considering packaging the videos into an electron app. This way ...

Having trouble executing a fetch request in Next.js

I am struggling to perform a fetch request using getStaticProps in Next.js. Despite following the documentation provided on their website, I am unable to console log the props successfully. My background is mainly in React, so I tried to adapt my approac ...

Is there a way to dynamically adjust the form action based on whether or not JavaScript is enabled?

Is there a way to make a form default to calling a JavaScript ajax function for output, but switch to a PHP page if the user doesn't have JavaScript enabled? <form class="form-inline" role="form" action="javascript:search();"> <div class=" ...

Create a project using Next.js and integrate it with the tailwindcss framework

My application utilizes TailwindCSS and NextJs. I am facing an issue where certain classes are not working after running npm run start, following a successful run of npm run dev. For example, the classes h-20 / text-white are not functioning as expected, w ...

Utilizing HTML5 Drag and Drop feature to track the initial position of the element being dragged

Currently, I am utilizing the HTML 5 Drag and Drop API to create a sortable list with auto scroll functionality. One crucial aspect I am trying to incorporate is the ability to detect which specific part of an element was grabbed by the user. Take a look ...

Pattern matching for a string with numerous repetitions using Regular Expressions

There's a [tree] and a cat and a [dog] and a [car] too. I am looking to find the words inside each set of square brackets. The resulting array will be tree, dog, car My attempt at using match(/\[(.*)\]/g) didn't work as expected. It ...

Conceal the navigation bar when scrolling to the top of the

Hey there! I'm looking for a way to hide my navigation bar when not scrolling, and then display it again once I start scrolling. Currently, I have two menus on this website: one with a white background and the other with a blue background. You can fi ...

Whenever I attempt to start my ReactJS project using the command line with `npm run it`, I keep encountering an error

Encountered an issue with the webpack-dev-server script while working on my project. Ensure that your node.js and npm versions are up to date. If they are, the problem might lie within the reactjs package rather than npm itself. Kindly inform the author ab ...