not able to get angular 2 scope inside call back functions - javascript

I need to update a array object inside a call back function ,i used the following lines but the values are set in the scope of call back loop not as angular variable so my view is not updated.(deviceval) value is changed if i print it inside the callback but outside the value is still the old one.
export class DashboardComponent implements OnInit {
hideTable: boolean = true;
public deviceVal:any;
constructor(private ref: ChangeDetectorRef) {}
ngOnInit() {
this.deviceVal = deviceData;
console.log(this.deviceVal);
var container = $('.map-canvas');
var options = {
center: new google.maps.LatLng(41.676258, -99.683199),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
gmap = new google.maps.Map(container[0], options);
this.drawChart(deviceData);
this.plotMarkers();
}
plotMarkers(){
$.each(deviceData, function(key, val) {
var controller=this;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(parseInt(val.lat), parseInt(val.lon)),
map: gmap,
});
google.maps.event.addListener(marker, 'click', function() {
this.deviceVal = val;
});
markerCache.push(marker);
})
}
}

The problem is here:
$.each(deviceData, function(key, val) {
var controller=this;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(parseInt(val.lat), parseInt(val.lon)),
map: gmap,
});
google.maps.event.addListener(marker, 'click', function() {
this.deviceVal = val;
});
markerCache.push(marker);
})
when you use function() as a callback function, the 'this' value is changed. You better read here about this.
You can fix this using arrow functions:
plotMarkers(){
$.each(deviceData, (key, val) => {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(parseInt(val.lat), parseInt(val.lon)),
map: gmap,
});
google.maps.event.addListener(marker, 'click', () => {
this.deviceVal = val;
});
})
}
But you have a lot of other problems, like: you don't need to use jQuery (to be honest, you should avoid jQuery in an ng2 app), the 'gmap' variable is not defined (you can set it as an property of the class, as you have done with 'deviceVal' for example), 'markerCache' was not defined too, there is no drawChart method, 'deviceData' is not defined inside plotMarkers().

I solved it by declaring a global variable before export component like
var controller;
and initialized it in ngoninit(),
controller = this;
and passed the controller to addlistener,
google.maps.event.addListener(marker, 'click', () => {
controller.deviceVal=[];
controller.deviceVal.push(val);
//console.log(controller.deviceVal+"end....................................")
});

Related

Trouble passing functions to other objects in Angular

I am having trouble passing functions to other objects in Angular. Specifically, I have created a function generateTile(coords) that populates a tile that will then be given to leaflet. This function is in a MapComponent method. I think I understand why this is an issue as this refers to a different context. However I don't know how to work around this issue.
generateTile(coords) {
...
return image;
}
private initMap(): void {
this.map = L.map('map', {
crs: L.CRS.Simple,
center: [0, 0],
zoom: 5
});
L.TileLayer.CustomMap = L.TileLayer.extend({
getTileUrl: function(coords) {
var img = this.generateTile(coords);
return img.src;
},
getAttribution: function() {
return "<a href='https://example.com'>Example</a>"
}
});
...
}
Use arrow function so you don't create a scope for this. You can read more about how this works in JavaScript, here is a link, for example.
getTileUrl: (coords) => {
var img = this.generateTile(coords);
return img.src;
};

Ionic 2: Unable to navigate from inner function

I'm trying to navigate to a page , upon clicking on a google map marker. I'm able to do it outside the inner function (Inside initializeMap function only), just having problems doing it in a inner function.
This is my constructor:
static get parameters() {
return [[NavController],[Platform]];
}
constructor(navController, platform, app) {
this.navController = navController;
this.platform = platform;
this.app = app;
this.map = null;
this.markers = [];
platform.ready().then(() => {
this.initializeMap();
});
}
Inside my initializeMap method contains the populateLocks method:
function populateLocks(auth,unauth,map){
for (var k in auth) {
(function (id) {
var auth = new google.maps.Marker({
icon: authImage,
map: map,
position: authLocks[id].latLng
});
google.maps.event.addListener(auth, 'click', function () {
//alert(auth[id].id);
this.navController.push(SettingsPage);
});
})
(k)
}
Using this.navController or navController throws me error like:
for this.navController.push
for navController.push
Either use () => instead of function ()
More information: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions
or use var self = this; outside the function and refer to self.navController instead of this.navController like so:
var self = this;
google.maps.event.addListener(auth, 'click', function () {
//alert(auth[id].id);
self.navController.push(SettingsPage);
});

Key in for loop has an unexpected value

I have a simple google map with multiple markers (4 in this case).
I want to add a "bubble" on click event. Markers are rendered fine, but the bubble (infowindow) show always on the last pin. I mean:
I click marker[1] - infowindow shows up on marker[3]
I click marker[[2] - infowindow shows up on marker[3]
etc.
I think that the problem is in the way I loop my array
Here is my loop, that iterates through 4 elements of array:
var key = 0;
var markers = new Array();
var infowindows = new Array();
for(key in myJson.hotels)
{
var newLatlng = new google.maps.LatLng(myJson.hotels[key].latitude,myJson.hotels[key].longitude);
markers[key] = new google.maps.Marker(
{
position: newLatlng,
map: map,
title: 'Hello World!'
});
// the code above works fine - it renders 4 pins o my map
infowindows[key] = new google.maps.InfoWindow(
{
content: contentString
});
google.maps.event.addListener(markers[key], 'click', function() {
//console.log(key); <-- this always return [3]
infowindows[key].open(map,markers[key]);
});
//console.log(key); <-- this always return the right key - 0,1,2,3
}
}
The function in addListener gets called asynchronously. When it gets called you dont know which value key has.
You can come arround this by storing the key in a closure.
google.maps.event.addListener(markers[key], 'click',
function (k) {
return function() { infowindows[k].open(map,markers[k]);
}(key)
});
I used a #phylax hint and I solved the problem this way:
I made a new function:
function addClickEventToMarker(aMap,aKey){
google.maps.event.addListener(markers[aKey], 'click', function() {
//console.log(key); <-- this always return [3]
infowindows[aKey].open(aMap,markers[aKey]);
});
}
and I call the function in my 'for' loop:
for(key in myJson.hotels)
{
var newLatlng = new google.maps.LatLng(myJson.hotels[key].latitude,myJson.hotels[key].longitude);
markers[key] = new google.maps.Marker(
{
position: newLatlng,
map: map,
title: 'Hello World!'
});
infowindows[key] = new google.maps.InfoWindow(
{
content: contentString
});
addClickEventToMarker(map, key);
}
}

accessing marker from listener-Google maps javascript API3.0

I have several markers (in an array) on my map, each with a custom ID tag i've given them.
What I want:
When I click on a marker, i wish to add it's ID to another array.
The problem:
The mouse event from Google does not have a target attribute, only the position, so I can't seem to access the ID directly.
I don't really want to have to resort to using the position to find the closest marker to it and returning it's ID this way, it's rather convoluted.
All help is appreciated
This is really easy, thanks to a feature in JavaScript and many other languages called a closure.
Simply put the code that creates the marker and sets up its event listener(s) insidea function, and call that function for each marker with the data needed for that specific marker. For example:
var places = [
{
id: 'one', lat: 1, lng: -1, name: 'First'
},
{
id: 'two', lat: 2, lng: -2, name: 'Second'
}
];
for( var i = 0; i < places.length; i++ ) {
addPlace( places[i] );
}
function addPlace( place ) {
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng( place.lat, place.lng ),
title: place.name
});
google.maps.event.addListener( 'click', function() {
alert( 'Clicked ' + place.id + ': ' + place.name );
});
}
I didn't test this Maps API code, but the specifics of the code are not important. What is important to understand is that place variable you see used in the code. This is the key part: that variable is accessible inside the event listener, simply because the event listener is nested inside the addPlace() function which has place as a parameter.
Note the difference between that code and code like this, which will not work:
for( var i = 0; i < places.length; i++ ) {
var place = places[i];
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng( place.lat, place.lng ),
title: place.name
});
google.maps.event.addListener( 'click', function() {
alert( 'Clicked ' + place.id + ': ' + place.name );
});
}
The only difference between the two is that the working version puts the loop body in a separate function which is called from the loop, instead of having all that code directly inside the loop. Having that code in a function that you call each time is what creates the closure, and that's what lets the inner event listener function "see" the variables in the outer function.
The great thing about closures is that you can use them in any similar situation. It isn't specific to the Maps API or the objects that the API uses. You may have even used them already and not realized it, for example in a setTimeout() call like this:
// Display an alert 'time' milliseconds after this function is called
function slowAlert( message, time ) {
setTimeout( function() {
alert( message );
}, time );
}
slowAlert( 'Howdy!', 1000 ); // Wait a second and then say Howdy!
Where the alert() call is made inside the setTimeout() callback function is made, it's using the closure on the slowAlert() function to pick up the value of the message variable that was passed into that function.
This should help. I added a customId property to the marker object and then in the marker click event I assign the id property to the new array.
function initialize() {
var map;
var centerPosition = new google.maps.LatLng(38.713107, -90.42984);
var options = {
zoom: 6,
center: centerPosition,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var bounds = new google.maps.LatLngBounds();
map = new google.maps.Map($('#map')[0], options);
var infoWindow = new google.maps.InfoWindow();
//marker array
var markers = [];
//sencondary array to store markers that were clicked on.
var markerIdArray = [];
for (i = 0; i < 6; i++) {
var lat = 38.713107 + Math.random();
var lng = -90.42984 + Math.random();
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(lat, lng),
customId: i //add a custom id to the marker
});
bounds.extend(marker.position);
google.maps.event.addListener(marker, 'click', function () {
//add the id to the other array.
markerIdArray.push(this.customId);
//log the content of the array to the console.
console.log(markerIdArray);
});
markers.push(marker);
}
map.fitBounds(bounds);
}
Here is an example of this in action.

Problems calling fitbounds outside jquery.each()

I'm working on a Google Map in JavaScript(v3).
I need to show some markers from XML, for which I use jQuery.
Here's the object and function, might save me time explaining:
var VX = {
map:null,
bounds:null
}
VX.placeMarkers = function(filename) {
$.get(filename, function(xml) {
$(xml).find("marker").each(function() {
var lat = $(this).find('lat').text();
var lng = $(this).find('lng').text();
var point = new google.maps.LatLng(parseFloat(lat),parseFloat(lng));
VX.bounds.extend(point);
VX.map.fitBounds(VX.bounds); //this works
var marker = new google.maps.Marker({
position: point,
map: VX.map,
zoom: 10,
center: point
});
});
});
//VX.map.fitBounds(VX.bounds); //this shows me the ocean east of Africa
}
So basically my problem is that I can't figure out how to do fitbounds from outside of the .each function, and doing it inside the function calls it for every marker which looks bad.
I declare the bounds when I initialize the map... haven't included the entire code because its like 300 lines.
Shouldn't I be able to use a value that I passed to a global object?
Edit: ah, I was calling it from outside of the get function!
The second call doesn't work because it is firing before the ajax get() returns.
Place the fitBounds inside the get() handler, but outside the each() function. Like so:
var VX = {
map:null,
bounds:null
}
VX.placeMarkers = function(filename)
{
$.get
(
filename,
function(xml)
{
$(xml).find("marker").each
(
function()
{
var lat = $(this).find('lat').text();
var lng = $(this).find('lng').text();
var point = new google.maps.LatLng(parseFloat(lat),parseFloat(lng));
VX.bounds.extend(point);
//VX.map.fitBounds(VX.bounds); //this works
var marker = new google.maps.Marker
({
position: point,
map: VX.map,
zoom: 10,
center: point
});
}
);
VX.map.fitBounds(VX.bounds); //-- This should work.
}
);
//VX.map.fitBounds(VX.bounds); //this shows me the ocean east of africa
}

Categories