I found mostly the kind of codes like the one below, which may work in javascript, but I can't get it to work in Typescript.
//javascript version
navigator.geolocation.getCurrentPosition( function(position){
ShowLocation( position, variable );
});
function ShowLocation(position, variable){
console.log(position, variable);
}
//what I've tried on typescript
map:any="test";
private GetCurrentLocation(): void {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function (position) {
/*something goes wrong here*/
this.ShowLocation(position, this.map);
});
} else {
alert("Geolocation is not supported by this browser.");
}
}
public ShowLocation(position: any, map: any): void {
console.log(position, map);
//do something with the position and map parameters
}
core.js:1448 ERROR TypeError: Cannot read property 'ShowLocation' of null
I don't know how to make this work in typescript. I don't understand why it gives that error.
edit: found the solution in the possible duplicate link, had to use bind for "this", thanks!
//working code
//what I've tried on typescript
map:any="test";
private GetCurrentLocation(): void {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function (position) {
this.ShowLocation(position, this.map);
}.bind(this));
} else {
alert("Geolocation is not supported by this browser.");
}
}
public ShowLocation(position: any, map: any): void {
console.log(position, map);
//do something with the position and map parameters
}