Tutorial: Implementing InfoWindows for Markers in Google Maps API V3 in a C# Web Page


Here's my newbie question, hope the formatting is correct :)
I'm working on an ASP.NET, C# application
that retrieves coordinates (Lat, Lon) from SQL and displays them as markers (which is working fine). However, when I try to add infowindow() to those markers, the map is not displaying properly. I want each marker to have its own infowindow() displayed.
This is the code in my CS page:

protected void Page_Load(object sender, EventArgs e)
{
    string markers = GetMarkers();
    Literal1.Text = @"<script type='text/javascript'>
 function initialize() {
 var mapOptions = {
 center: new google.maps.LatLng(41.43242, -89.209343),
 zoom: 5,
 mapTypeId: google.maps.MapTypeId.ROADMAP
 };
 var image = new google.maps.MarkerImage('pic/marker.png', null, null, null, new google.maps.Size(30, 42));
 var myMap = new google.maps.Map(document.getElementById('mapArea'),
 mapOptions);" + markers + @"}
 </script>";
}

protected string GetMarkers()
{
    string markers = "";
    using (SqlConnection con = new SqlConnection("Data Source=localhost;Initial Catalog=web1;Integrated Security=True"))
    {
        SqlCommand cmd = new SqlCommand("SELECT Lat, Lan FROM Location", con);
        con.Open();
        SqlDataReader reader = cmd.ExecuteReader();
        int i = 0;

        while (reader.Read())
        {
            i++;
            markers +=
            @"var marker" + i.ToString() + @" = new google.maps.Marker({ icon: image,
            position: new google.maps.LatLng(" + reader["Lat"].ToString() + ", " +
            reader["Lan"].ToString() + ")," +@"map: myMap});";
        }
    }
    return markers;
}

Answer №1

Great start! I typically use a string builder to manipulate the output and then assign it to Literal.Text. In this example, MarkerCluster is being utilized and you can find it at the following location:

<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerclusterer/1.0/src/markerclusterer.js"></script>

Best of luck with your implementation.

StringBuilder sb = new StringBuilder();

sb.Append("<script type='text/javascript'>");
sb.Append("var mapOpts = {mapTypeId: google.maps.MapTypeId.ROADMAP};");
sb.Append("var map = new google.maps.Map(document.getElementById(\"map\"), mapOpts);");

// Additional JavaScript logic goes here...

sb.Append("</script>");

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

When using the mui joy library, obtaining the input value upon submission may result in the retrieval of an "unidentified" response

Struggling to fetch user input for 2FA authentication using the mui JoyUI library. Attempted using e.target and searching for input value with no success. Clearly missing something in the documentation. Also gave 'useRef' a shot, but the code sni ...

The action is not being added to the HTML when the click event is triggered

I'm developing a GIF generator, with the aim of generating clickable buttons that will dynamically add 10 gifs based on the search term to the page. Although the click event is triggering the console log, it's not adding divs with gif images and ...

Slow loading ASP.NET website in Internet Explorer 10

The dilemma My ASP.NET website runs smoothly on Internet Explorer 8, but experiences extreme slowness on Internet Explorer 10. The Issue In IE 8, a postback or button click event takes about 1.5 seconds to complete. However, in IE 10, it takes at least ...

What could be the reason for the onClick event functioning only once in HTML?

Below is the code snippet containing both HTML and JavaScript. However, the issue I am facing is that the onclick event only seems to work for the first <li>. <!DOCTYPE html> <html> <body> <ul class="list"> <li ...

How to switch the code from using $.ajax() to employing $.getJSON in your script

How can I convert this code from using AJAX to JSON for better efficiency? AJAX $('#movie-list').on('click', '.see-detail', function() { $.ajax({ url: 'http://omdbapi.com', dataType: 'json', d ...

Strange yellow border appears when key is pressed in Quasar's QLayout

While working on a project with the quasar framework and electron.js, I encountered a strange bug where pressing a key causes the application frame to display a persistent yellow border. This border cannot be overridden, removed, or selected using devtools ...

The React Material UI Autocomplete, when combined with React-window, causes the list to re-render at the top

Looking for some assistance with React since I'm new to it. Having trouble with the Material-ui autocomplete component and need help from experienced React developers. The issue I'm facing is that when I choose an option from the autocomplete dr ...

Incorporating jquery-ui Datepicker with dynamic text input functionality

In my table list, I have multiple input fields with the jQuery datepicker implemented. Each input field is assigned the class "datepicker" and a unique ID number. When clicked on, the datepicker pops up allowing for date selection to be inserted into the f ...

How to automatically set the radio button as "checked" with Javascript upon loading the page

With the dark mode switch javascript from Bootstrap 5 (https://getbootstrap.com/docs/5.3/customize/color-modes/#javascript), I am attempting to ensure that a radio button is set to "checked" when the page loads, as well as when the color mode is changed. ...

Error: Attempted to access 'embed' before it was initialized (hi)

module.exports = { name: "slowmode", description: "Set the slowmode of a channel.", execute(message, args, Discord) { if(!message.member.hasPermission("ADMINISTRATOR")) { return message.reply(&q ...

Properly executing a for loop

I have devised a method to transform Swagger 1 documentation into Swagger 2. This involves utilizing an array of resources as input for the conversion process. However, I have encountered an issue where the code seems to be skipping ahead and jumping to ...

Error encountered: Unknown error while using Microsoft Edge WebDriver

When attempting to utilize Microsoft Edge automation with Selenium, I keep encountering the following exception: OpenQA.Selenium.WebDriverException: Unexpected error. Unknown error The NuGet package I am using is Selenium.WebDriver.MicrosoftDriver vers ...

Press the Enter key to submit

Encountering issues while trying to enter an event. Despite reviewing several posts on this matter, a solution has not been found yet. The project needs to function properly in Chrome, FF & IE (8,9,10,11), but it is currently not working on any browser. T ...

Is there a way to transfer a JSON object to Excel using Nextjs/React?

How can I create a button that exports data from a JSON object to multiple file formats, including Excel (.xlsx)? "data": [ { "id": 1, "temaIndicador": "Indian", "codigo": "001", "observacion ...

Is there a way to effortlessly refresh a viewpage with fresh data directly from Firebase?

I am trying to update my HTML page with new data from Firebase in real time without having to refresh the entire page. However, I am facing issues where the view is not updating automatically. How can I achieve this? In my JavaScript file, I query Firebas ...

Tips on applying border to unique marker icon in Angular2 using agm-marker

https://i.sstatic.net/HH36B.png Hello everyone, I've been working on a project and need some assistance. My goal is to dynamically add custom marker icons to specific lat/lng coordinates, each with additional values such as a "color name" for border ...

What is the best way to iterate through one level at a time?

Imagine a scenario where the structure below cannot be changed: <xml> <element name="breakfast" type="sandwich" /> <element name="lunch"> <complexType> <element name="meat" type="string" /> <element name="vegetab ...

Using jQuery to include a sub-object in the "data" object for each AJAX request made on the webpage

Is there a way to enhance the functionality of jQuery.ajax by including a static sub-data object in every ajax request automatically? For instance, for an ajax request like this: jQuery.ajax({ url: 'request_file.php', data: { da ...

Creating a full-width tab card with Bootstrap-Vue: A step-by-step guide

I stumbled upon something similar in the documentation for bootstrap-vue: A card with tabs: https://i.sstatic.net/HoVEC.png Now, how can I style the tabs to look like this: https://i.sstatic.net/dbsRj.png This is my current code: <b-card no-body ...

Is it possible to include numbers and commas in JQuery Validation?

I have implemented a jQuery validation plugin to validate the fields of a form. One specific requirement is to validate a field to only allow commas and numbers. Below is the HTML code snippet: <input type="text" placeholder="Number of Employees" requ ...