Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window.onload work but Chrome console says: Uncaught TypeError: window.onload is not a function

I want to run getLocation() method at the page load. I added: window.onload(getLocation()); and the function is invoked as I desire but Chrome console says:

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

The view, the window.onload(getLocation()); is at the bottom:

@{
    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>
}
like image 973
Yoda Avatar asked Apr 28 '15 18:04

Yoda


1 Answers

The way you've written your code, it's not running onload, it's just running when the parser hits it. Because you wrote getLocation() rather than just getLocation, it executes the function.

If you are certain there will be nothing else to be fired on load, you can do window.onload=getLocation;. If you want to make sure you play nicely with other code (including third-party frameworks/libraries) that might use the load event, you can do something like this:

window.addEventListener('load', getLocation);

Note that that code won't work in IE8. If you need to support IE8, check for addEventListener() and if it is not found, check for and use attachEvent() instead:

   if (window.addEventListener) {
      window.addEventListener('load', getLocation);
   } else if (window.attachEvent) {
      window.attachEvent('onload', getLocation);
   } else { 
      window.onload = getLocation;
   }
like image 188
Trott Avatar answered Sep 18 '22 12:09

Trott