How to show google maps in ASP.NET C#

Ivan Ben Ker picture Ivan Ben Ker · May 4, 2017 · Viewed 8.8k times · Source

I am working on adding the google maps control into an ASP.NET C# page. I have gotten the API key from google and I was just testing the page out but it seems that the map is not showing. And my end result is to have inputs using textboxes for Latitude and longitude and upon clicking the submit button, the map brings me to the specified location. On the frontend, I have this:

<script>
    var map;
    function initialize() {
        map = new google.maps.Map(document.getElementById('map'), {
            center: new google.maps.LatLng(48.1293954, 11.556663), // Munich Germany
            zoom: 10
        });
    }

    function newLocation(newLat, newLng) {
        map.setCenter({
            lat: newLat,
            lng: newLng
        });
    }

    google.maps.event.addDomListener(window, 'load', initialize);
</script>
<form id="form1" runat="server">
    <asp:ScriptManager ID="sManager" runat="server" />
    <asp:UpdatePanel ID="pnlTest" runat="server">
        <ContentTemplate>
            <div style="height: 60%;" id="map"></div>

            <asp:TextBox ID="txtLat" runat="server" />
            <asp:TextBox ID="txtLong" runat="server" />
            <asp:Button ID="btnSubmit" Text="Submit" runat="server" />
        </ContentTemplate>
    </asp:UpdatePanel>
</form>

I have not done the button click event because i want to get the above up first.

Answer

laylarenee picture laylarenee · May 4, 2017

The problem is that your UpdatePanel has no height when the map is rendered. If you specify a height for your control, the map will be visible:

<asp:UpdatePanel ID="pnlTest" runat="server" style="height:400px;">

The Google documentation says you must set a height explicitly:

Note that divs usually take their width from their containing element, and empty divs usually have 0 height. For this reason, you must always set a height on the div explicitly.