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>
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With