Window.onload works, but the Chrome console says: Uncaught TypeError: window.onload is not a function

I want to run the method getLocation()when the page loads. I added: window.onload(getLocation());and the function is called as I wish, but the Chrome console says:

 Uncaught TypeError: window.onload is not a function(anonymous function) @ (index):116

The view window.onload(getLocation());is below:

@{
    ViewBag.Title = "Home Page";
}


<div id="demo"></div>
<h2>Gecoding Demo JavaScript: </h2>
<div id="map" style="height: 253px ; width: 253px" />


@section Scripts {
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
    <script>
        var x = document.getElementById("demo");
        function getLocation() {
            if (navigator.geolocation) {
                var position = navigator.geolocation.getCurrentPosition(showPosition);

            } else {
                x.innerHTML = "Geolocation is not supported by this browser.";
            }
        }
        function showPosition(position) {
            x.innerHTML = "Latitude: " + position.coords.latitude +
            "<br>Longitude: " + position.coords.longitude;
            InitializeMap(position)
        }
        var map;
        var geocoder;
        function InitializeMap(position) {

            alert(position.coords.latitude+"");
            var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
            var myOptions =
            {
                zoom: 8,
                center: latlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                disableDefaultUI: true
            };
            map = new google.maps.Map(document.getElementById("map"), myOptions);
        }

        window.onload(getLocation());
    </script>
}
+4
source share
1 answer

As you wrote your code, it does not work onload, it just works when the parser hits it. Since you wrote getLocation(), and not only getLocation, it performs this function.

, , window.onload=getLocation;. , ( /), , - :

window.addEventListener('load', getLocation);

, IE8. IE8, addEventListener(), , attachEvent():

   if (window.addEventListener) {
      window.addEventListener('load', getLocation);
   } else if (window.attachEvent) {
      window.attachEvent('onload', getLocation);
   } else { 
      window.onload = getLocation;
   }
+8

All Articles