Search code examples
javascriptc#asp.netgoogle-mapslinq-to-entities

Cannot read property 'lat' of undefined using google maps


I am making an application in which i have the database of assets and i need to look at assets in map which have certain parameters. I have written the code but then when I select any value one of the drop down boxes it shows the error Cannot read property 'lat' of undefined. The map appears at first but after i select a certain value in dropdown it disappears. Any help will be appreciated. Thanks in Advance. I have added cs file and aspx file also.

 protected void Page_Load(object sender, EventArgs e)
      {
          if (!this.IsPostBack)
    {
        BindCS();
        BindCC();
        BindAG();
        List<LUT_Assets_Masters> dt = this.GetData();
        rptMarkers.DataSource = dt;
        rptMarkers.DataBind();
    }
}
private List<LUT_Assets_Masters> GetData()
{
    AssetTaggingEntities context = new AssetTaggingEntities();
    List<LUT_Assets_Masters> am1 = null;
    if (DDSearch.SelectedValue == "1" && DDStatus.SelectedIndex >= 0 && DDCondition.SelectedIndex >= 0 && DDGroup.SelectedIndex >= 0)
    {
        am1 = (from am in context.LUT_Assets_Masters
               where am.CSID == DDStatus.SelectedIndex
                     && am.CCID == DDCondition.SelectedIndex
                     && am.AGrpID == DDGroup.SelectedIndex
               select am).ToList();
    }

    else
    {
        am1 = (from am in context.LUT_Assets_Masters select am).ToList();
    }
    return am1;

}
protected void DDS_SelectedIndexChanged(object sender, EventArgs e)
{
    List<LUT_Assets_Masters> dt = this.GetData();
    rptMarkers.DataSource = dt;
    rptMarkers.DataBind();
}

protected void DDGroup_SelectedIndexChanged(object sender, EventArgs e)
{
    List<LUT_Assets_Masters> dt = this.GetData();
    rptMarkers.DataSource = dt;
    rptMarkers.DataBind();
}

protected void DDCondition_SelectedIndexChanged(object sender, EventArgs e)
{
    List<LUT_Assets_Masters> dt = this.GetData();
    rptMarkers.DataSource = dt;
    rptMarkers.DataBind();
}

protected void DDStatus_SelectedIndexChanged(object sender, EventArgs e)
{
    List<LUT_Assets_Masters> dt = this.GetData();
    rptMarkers.DataSource = dt;
    rptMarkers.DataBind();
}
protected void DDSearch_SelectedIndexChanged(object sender, EventArgs e)
{
    if (DDSearch.SelectedValue == "1")
    {
        Search.Visible = true;
        BArea.Visible = false;
    }

    if (DDSearch.SelectedValue == "2")
    {
        Search.Visible = false;
        BArea.Visible = true;
    }
}

aspx file

 <script async 
src="https://maps.googleapis.com/maps/api/js?key=KEY&callback=initMap">
 </script>

<script type="text/javascript">
    var markers = [
    <asp:Repeater ID="rptMarkers" runat="server">
        <ItemTemplate>

 {
                "Name": '<%# Eval("AID") %>',
                "lat": '<%# Eval("Current_Location_Y") %>',
        "lng": '<%# Eval("Current_Location_X") %>',
            "description": '<%# Eval("Description") %>'
        }

</ItemTemplate>

  <SeparatorTemplate>

 ,
  </SeparatorTemplate>

   </asp:Repeater >

   ];
  </script>
<script type="text/javascript">                   
    window.onload = function initMap() {                                
        var mapOptions = {              
            center: new google.maps.LatLng(markers[0].lat, markers[0].lng),  
            zoom: 8,                                                     
            mapTypeId: google.maps.MapTypeId.ROADMAP         
        };
        var infoWindow = new google.maps.InfoWindow/*()*/;                   

        var map = new google.maps.Map(document.getElementById("map"), mapOptions);
        for (i = 0; i < markers.length; i++) {                                   
            var data = markers[i]                                           
            var myLatlng = new google.maps.LatLng(data.lat, data.lng);        
            var marker = new google.maps.Marker({               
                position: myLatlng,                                
                map: map,                                        
                title: data.title                             
            });
            (function (marker, data) {                            
                google.maps.event.addListener(marker, "click", function (e) {
                    infoWindow.setContent(data.Name);                     
                    infoWindow.open(map, marker);                     
                });
            })(marker, data);         
        }
    }

  </script>
<div id="DDmap" style="float:left; height: 200px">
 <div id="side" style=" background-color: white;
font-size: 18px;
text-align: center; padding: 50px 20px 50px 20px;" class="auto-style3">
                     <asp:DropDownList ID="DDSearch" runat="server" placeholder="Select By" text-align="center"  class="form-control"  Height="30px" style="float:right;"  Width="50%" margin="2px" AutoPostBack="True" OnSelectedIndexChanged="DDSearch_SelectedIndexChanged">
                     <asp:ListItem Selected="True" Value="0" Text="Select By"></asp:ListItem>
                     <asp:ListItem  Text="Locate" Value="1"></asp:ListItem>
                     <asp:ListItem  Text="Buffer" Value="2"></asp:ListItem>

                                       </asp:DropDownList>
                               <br />  <br />
           <br />  <br />
                        <asp:Panel ID="Search" runat="server" Visible="False">
              <label for ="Search" style="float:right">

                 <asp:DropDownList ID="DDCondition" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DDCondition_SelectedIndexChanged">
</asp:DropDownList>
                  <br /><br />
<asp:DropDownList ID="DDStatus" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DDStatus_SelectedIndexChanged">
</asp:DropDownList>
                  <br /><br />
                    <asp:DropDownList ID="DDGroup" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DDGroup_SelectedIndexChanged">
</asp:DropDownList>
              </label>
           <br /><br />
          </asp:Panel>
      </div>

Solution

  • At some point, you are trying to read the latitude of an object, but the object itself is undefined. One of the lines in your JavaScript accesses the first element of the array of markers, without checking if the array is not empty:

    var mapOptions = {              
        center: new google.maps.LatLng(markers[0].lat, markers[0].lng),  
        zoom: 8,                                                     
        mapTypeId: google.maps.MapTypeId.ROADMAP         
    };
    

    If there are no markers, then markers[0] will evaluate to undefined, and you will get the error Cannot read property 'lat' of undefined. I would recommend putting in a check first, and if the list is empty, provide a default latitude and longitude:

    var center = new google.maps.LatLng(0, 0);
    if (markers.length > 0)
        center = new google.maps.LatLng(markers[0].lat, markers[0].lng);
    
    var mapOptions = {              
        center: center,  
        zoom: 8,                                                     
        mapTypeId: google.maps.MapTypeId.ROADMAP         
    };
    

    It looks like as soon as you select an item in the drop-down list, the following condition becomes true:

    DDSearch.SelectedValue == "1" && DDStatus.SelectedIndex >= 0 && DDCondition.SelectedIndex >= 0 && DDGroup.SelectedIndex >= 0
    

    So instead of returning all LUT_Asset_Masters, GetData() returns only the LUT_Asset_Masters that match your filters, which turns out to be an empty list. You need to double-check that query - make sure the data you are querying for exists, and the query returns what you expect it to return.