简体   繁体   中英

Unable to bind java script function with Panel's OnLoad event

I am in the initial stages in working with java script and I just wrote a small application in asp.net for using the Google Maps APIv3. I want to display the map in a panel. This is the code that I wrote but I have problem in binding the java script with the Panel's OnLoad event:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head runat="server">
  <title>Map Test</title>
    <style type="text/css">
      html{height:100%}
      body{height:100%; margin:0;padding:0}
      #map_can{height:100%}
    </style>
  <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzawerwerQ55N500rxxxxdPNvMoQ74aRYO30Wo&sensor=true">
  </script>
  <script type="text/javascript">
     function init()
     {
       var mapoptions=
          {
            center: new google.maps.LatLng(17.379064211298, 78.478946685791),
            zoom:8,
            mapTypeId: google.maps.MapTypeId.ROADMAP
          };
       var map=new  google.maps.Map(document.getElementById("map_can"),mapoptions);
     }
  </script>
</head>
<body>
  <form id="form1" runat="server">
    <asp:Panel  OnLoad="init()" ID="Panel1" runat="server" 
      style="z-index: 1; left: 37px; top: 59px; position: absolute; height: 273px; width: 565px">
      <div id="map_can" style="width:100%; height:100%"></div>
    </asp:Panel>
  </form>
</body>
</html>

Error: ASP.default_aspx' does not contain a definition for 'init'

I guess I am binding it the wrong way. Suggestions please.

The Panel OnLoad property is for setting server side handler for Load event (it should be method in your page class).

There is no way of setting client side load event on Panel control as it generates DIV element (and DIV element doesn't support load event).

A primitive way out of this is to use client side load event of BODY element:

<body onload="init();" >
    ...
</body>

But a lot better way is to wait for DOM readiness to invoke a function. An easy and cross browser way of doing this is usage of library like jQuery :

<script type="text/javascript">
    $(document).ready(function() {
        var mapoptions = {
            center: new google.maps.LatLng(17.379064211298, 78.478946685791),
            zoom: 8,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new  google.maps.Map(document.getElementById("map_can"),mapoptions);  
    });
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM