Getting events of a JS object using jQuery - javascript

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

Related

Mapbox marker click event in Ionic 2 / Angular 2

I'm getting started with Ionic 2 / Angular 2 and trying to implement Mapbox into my app.
To display custom markers (code example here) Mapbox expects a DOM element, which, as far as I understand it, is not really the Angular way. I want to add a click event on the marker but because Mapbox uses elements, I'm not entirely sure how to approach this cleanly "the Angular way".
Basically, this is the latest version (showing the map and the marker works, but predictably when I click the marker the event listener can't find this.onMarkerClicked):
export class HomePage {
//(...)
refreshMapPosition() {
/*Initializing Map*/
mapboxgl.accessToken = this.config.mapbox_public_token;
this.map = new mapboxgl.Map({ /*https://www.mapbox.com/mapbox-gl-js/api/#map*/
style: 'mapbox://styles/mapbox/light-v9',
center: [this.Coordinates.longitude, this.Coordinates.latitude],
zoom: 16,
pitch: 80,
minZoom: 7.5,
maxZoom: 17,
container: 'map',
interactive: false,
});
var elCreature = document.createElement('div');
elCreature.className = 'icon-creature alpaca';
elCreature.addEventListener('click', function() {
this.onMarkerClicked();
});
var markerCreature = new mapboxgl.Marker(elCreature, {offset: [-20, -20]})
.setLngLat([this.Coordinates.longitude, this.Coordinates.latitude])
.addTo(this.map);
}
onMarkerClicked() {
console.log("click");
}
}
I'd be much happier if it was possible to have elCreature coming from a component, where I could use <div class="icon-creature alpaca" (click)="onMarkerClicked"></div>. What's the best approach there?
// on your marker HTML
var _self = this;
var _data = this.value;
el.addEventListener('click', function() {
self.markerClicked(_data);
});
// angular method
markerClicked(value){
console.log(value);
}
So I found something that maybe could help you, I created a marker as the documentation mentioned and then I got the element of that market with the getElement() function, after that I added the event to the marker, I do not know if it works with various markers but you can try.
var marker = new mapboxgl.Marker()
.setLngLat([lng, lat])
.addTo(this.map);
marker.getElement().addEventListener("click", function(){
console.log("function");
});
After sleep a while I found that there another thing that you can use, so you can create a Popup first and then add that Popou to a Marker object with the setPopup() method and actually it like an onClick event, because, when you click the Marker the Popup appears. Here is an example.
var popup = new mapboxgl.Popup()
.setLngLat(coordinates)
.setHTML("<h1>Hello</h1>");
var marker = new mapboxgl.Marker()
.setLngLat(coordinates)
.setPopup(popup)
.addTo(this.map);
The variable "coordinates" is an array, such that coordinates = [lng,lat], and this.map is just a variable under my Angular class that call to the mapboxgl.Map object.
You have to know that I am using Ionic 4 in this case. If you need more information please tell me.
Regards.

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

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

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);
});
});

cakephp: access hidden field value set in ctp, in controller without form post

I am working in cakephp and javascript. Following is the scenario:
on map icon click, a jquery finction is called which displays the google map. Now through javascript, the user can drag n change the current marker position in google map. The values are set in view also. But how do i access these values(latitude, longitude) in controller?
I wish to set the latitude and longitude in session variable but i cant do that i mean icant set session variable in javascript n use it in controller.
Following is my code:
function initialize() {
var latLng = new google.maps.LatLng(lat,long);
var map = new google.maps.Map(document.getElementById('mapCanvas'), {
zoom:8,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: latLng,
title: 'Point A',
map: map,
draggable: true
});
// Update current position info.
//alert(" initilize");
updateMarkerPosition(latLng);
geocodePosition(latLng);
// Add dragging event listeners.
google.maps.event.addListener(marker, 'dragstart', function() {
//updateMarkerAddress('Dragging...');
// alert("dragStart"+marker.getPosition()); // access this value in controller
});
google.maps.event.addListener(marker, 'drag', function() {
// updateMarkerStatus('Dragging...');
updateMarkerPosition(marker.getPosition());
alert(marker.getPosition()); // access this value in controller
});
google.maps.event.addListener(marker, 'dragend', function() {
// updateMarkerStatus('Drag ended');
geocodePosition(marker.getPosition());
alert(marker.getPosition()); // access this value in controller
});
}
in controller:
public function map()
{
//access lat, long here
}
how do i do that?
Connecting JavaScript with PHP can be done with AJAX technique.
Like this, your JavaScript code will call a concrete action in a controller and once in there, you can save it in sessions or do whatever you want to do with it.
You can call the action every X seconds or on any change, it depends on when you want to call it and the possible events you can catch from the user.
This is an example of what i mean:
$(document).ready(function(){
//calling the function every 30 seconds
setInterval(function(){
getUserSavings();
}, 30*1000);
});
function getUserSavings(){
$.post("http://"+ document.domain + "/users/getSavings.json",
function(dat){
//do whatever you want with the resulting data (dat)
$('#totalSavings span').html(dat['result']['savings']);
});
}
It is not needed to use the extension json but it enables you to call the action without having to define a view. For more info you can take a look at the documentation.

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