How to stop run javascript function when asp.net webform loaded? - javascript

I'm write this code for show my position on the map:
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script>
function initialize(x, y) {
alert(x);
alert(y);
var mapProp = {
center: new google.maps.LatLng(x, y),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
up code run the initialize function when page load or postback,but i write this code for asp button:
Page.ClientScript.RegisterStartupScript(this.GetType(), "beh", "initialize(38.076306,46.279637);", true);
and i want when button fire,send value to function and java script function change the map position,it's work,but when button fire,function run ,and run again when web form loaded!,and in first time show correct position,but when page load event occurred,send null value to function and show empty position, i think when run java script function in asp button fire,and not run java script function when page load occurred?

The problem with your code is the execution order of the code blocks. Execution time of code that is added via the ClientScriptManager.RegisterStartupScript according to the msdn:
The script block added by the RegisterStartupScript method executes when the page finishes loading but before the page's OnLoad event is raised.
So, you could solve your problem by adding a boolean variable in your script tag (which get's executed while the page is loading), set it to false initially and change it to true in your button click handler (which is executed once the page has finished loading). Then in your window.onload event listener, check if the variable is false. If it is, you can initialize the map.
So, your javascript would change to this:
<script>
var isButtonClick = false;
function initialize(x, y) {
var mapProp = {
center: new google.maps.LatLng(x, y),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
}
google.maps.event.addDomListener(window, 'load', function () { if(!isButtonClick)initialize(0, 0) });
</script>
and your button click handler to this:
void ButtonClick(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "beh", "isButtonClick=true;initialize(38.076306,46.279637);", true);
}
I tested it locally and it worked fine

Related

Load Google Map in new window by appending a button

I'm trying to append a button to a page that when clicked will display my google map in a new page. I have a button that when clicked either gives an error or gives a blank page.
My code:
$('.content--body__wrapper').append('<button id="show-map" />')
$('.content--body__wrapper').append(`<script>
document.getElementById("show-map").addEventListener("click", function(){
var center = {lat: -25.363, lng: 131.044};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: center
});
var marker = new google.maps.Marker({
position: center,
map: map,
});
})
</script>`);
$('.content--body__wrapper').append(`<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBcwtM8EBe7BE1NyPbU5SDYVYoBBtbtpTI&libraries=drawing" asyncdefer></script>`);
Error Code:
Edit: I took the callback out of the script source and I still don't get a page to load but I do have a lot less errors.
$('.content--body__wrapper').append('<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBcwtM8EBe7BE1NyPbU5SDYVYoBBtbtpTI&libraries=drawing&callback=initMap" async defer></script>');
In this line you say : when the API is loaded run the function called InitMap.
The problem is that this function is not definied in your js.
So remove this callback to use the documentReady event or remove documentReadyListener and create a function name initMap

The function does not run in an external file

I work on a wordpress page, using the google maps api.
my file functions:
function liceoucatolica_estilo() {
// API google maps
wp_enqueue_script('maps', 'https://maps.googleapis.com/maps/api/js?key=AIzaSyAJq5xO31rYRAqv5h6yUZTOaHwDX2zjNlo&callback=initMap', array(), false);
// Cargar scripts
wp_enqueue_script('main', get_template_directory_uri() . '/js/main.js',null,false);
}
add_action( 'wp_enqueue_scripts','liceoucatolica_estilo');
my file main.js (In which is the function of the map):
window.onload = function(){
function initMap(){
var campus = {lat: 4.634241, lng: -74.068513};
// Create a map object and specify the DOM element for display.
var map = new google.maps.Map(document.getElementById('mi_mapa'), {
center: campus,
scrollwheel: false,
zoom: 17
});
var marker = new google.maps.Marker({
position: campus,
map: map,
title: 'Liceo de la Universidad Católica'
});
}
};
If I copy the function in the header or footer if it works, but if I only leave it in Main.js does not work
There can be two causes:
1.- You're declaring the function when the window.onload event has already happened, so it keeps listening for something that will never happen.
2.- Google maps's script resolves before you get the chance to declare function initMap.
I'd try switching the order of the scripts, and removing window.onload at all. Just declare the initMap function in the global scope.

How can I detect when an element dynamically added has loaded?

Edit: added Handlebar template loading
I am trying to detect when a dynamically added element has been loaded (from a handlebars template), but the event never fires.
Here is the code:
var source = $('#mapTemplate').html();
var template = Handlebars.compile(source);
$('#wrapper').fadeOut(function() {
$('#wrapper').html(template());
$('#wrapper').fadeIn();
});
$('body').on('ready', '#mapCanvas', function() {
alert('Ready')
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8
};
var map = new google.maps.Map(document.getElementById("mapCanvas"),mapOptions);
})
What am I doing wrong?
Your template is available on the page immediately after the call to insert handlebar's template
$('#wrapper').html(template());
//#mapCanvas should be available
However, you're probably getting an error because you are telling the div to fade in and jQuery makes it invisible initially. Be sure to wait until the fadeIn finishes.
var source = $('#mapTemplate').html();
var template = Handlebars.compile(source);
$('#wrapper').fadeOut(function() {
$('#wrapper').html(template());
$('#wrapper').fadeIn(function() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8
};
var map = new google.maps.Map(document.getElementById("mapCanvas"),mapOptions);
});
});
As you have discovered, there is no "ready" event when a template is loaded.
The usual solution to knowing when anything that is dynamically loaded is ready is to supply a completion callback function to the code that is doing the loading. When that callback is called, the content is available in the page. I don't know exactly how you're loading the handlebars template, but the handlebars functions I see for loading a template, all take a callback argument that is called after the template has been successfully loaded. You would then trigger your map logic from within that callback.
If you show us the code you're using for loading the template, we can be much more specific.
Now, that you've shown us the code, your template is already preloaded and you can restructure you code like this to add the mapping stuff as soon as the fadeIn has finished:
var source = $('#mapTemplate').html();
var template = Handlebars.compile(source);
$('#wrapper').fadeOut(function() {
$('#wrapper').html(template()).fadeIn(function() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8
};
var map = new google.maps.Map(document.getElementById("mapCanvas"),mapOptions);
});
});

Getting events of a JS object using jQuery

Hi I am using the following code to
var view = new storeLocator.View(); //it has an event called load
$(view).on("load",function(){
alert("Gochcha!!");
return true;
})
But I don know why I never get the alert to fired ? Can anybody please tell me what am I missing ?
I think the code snippet din make things clear. Lemme share the entire code I am trying:
google.maps.event.addDomListener(window, 'load', function() {
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(-28, 135),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var panelDiv = $('#panel');
var data = new MyDataSource;
var view = new storeLocator.View(map, data, {
geolocation: true,
features: data.getFeatures()
});
$(view).on("load",function(){
alert("Gochcha!!");
return true;
})
});//End of map load
What I am trying is not Triggering the event, but binding my function to an event of a javascript object, so that whenever the event fires I get my function called first and then continue what it was suppose to do. The even does fire as I see the map and the data get loaded but I am not getting my function to get working.
make sure the context in which you are raising the event is the view otherwise this wont get caught

Adding Event Listener causes Google Map to freeze

I am attempting to create a google map with markers on my page. I have an unordered list where each item has data attributes for latitude, longitude and title. Using JQuery I pull these values and produce a marker on the map for each item in the list. Everything seems to work OK except google maps will not load tiles as you pan around the map.
This is how I initialize the map:
var map;
// initialize google map
$(function () {
var myOptions = {
zoom: 10,
center: new google.maps.LatLng(CoordinatesLat, CoordinatesLong),
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
}
// initiate map
map = new google.maps.Map($("#map")[0], myOptions);
// when map is loaded, add events and behaviors to it
google.maps.event.addListenerOnce(map, 'tilesloaded', addEventsToMap(".event")); //commenting this line prevents GMAP problems
});
FYI - before I was using maps.event.addListener() and the map would work momentarily and then become completely unresponsive. Changing it to maps.event.addListenerOnce() stopped the freezing but still has the tile loading problem.
And this is the callback, where evidently I've done something wrong:
//add events from event list to map. add behavior to events ie. mouseover
function addEventsToMap(selector) {
$(selector).each(function (i, $e) {
$e = $($e);
var latlng;
if ($e.attr("data-geo-lat") && $e.attr("data-geo-long")) {
latlng = new google.maps.LatLng($e.attr("data-geo-lat"), $e.attr("data-geo-long"));
$e.marker = new google.maps.Marker({
position: latlng,
map: map,
title: $e.attr("data-title")
});
google.maps.event.addListener($e.marker, 'click', function () { window.location = $e.attr("data-href"); });
google.maps.event.addListener($e.marker, 'mouseover', function () { $e.addClass("event-hover"); });
google.maps.event.addListener($e.marker, 'mouseout', function () { $e.removeClass("event-hover"); });
//when mouse hovers over item in list, center map on it's marker
$e.mouseenter(function () {
map.panTo(latlng);
});
}
});
}
Any idea what could be causing this?
I see a problem, though I'm not sure if it's the issue here. If you examine this line:
google.maps.event.addListenerOnce(map, 'tilesloaded', addEventsToMap(".event"));
What you are intending to do is call your 'addEventsToMap' once the map is loaded, but instead what you are doing is calling the function and then assigning the return value of that as a listener.
You need this instead, and I think it shouldn't crash anymore.
google.maps.event.addListenerOnce(map, 'tilesloaded', function() {
addEventsToMap(".event");
});
If that doesn't work, I would recommend looking at the Javascript Console of whatever browser you are using, to see what error is happening to make the map crash.

Categories

Resources