boxed__l
boxed__l

Reputation: 1336

Invoking a JS function defined in Component Template from Angular2

This is the JS code which needs to be called after Map Component in loaded by Angular2. Code is defined in the Component Template.

<script>
   var x = document.getElementById("demo");
   function getLocation() {
       if (navigator.geolocation) {
           navigator.geolocation.getCurrentPosition(showPosition,showError);
       } else {
           x.innerHTML = "Geolocation is not supported by this browser.";
       }
   }

   function showPosition(position) {
       x.innerHTML = "Latitude: " + position.coords.latitude + 
       "<br>Longitude: " + position.coords.longitude; 
   }

   function showError(error) {
        switch(error.code) {
            case error.PERMISSION_DENIED:
                x.innerHTML = "User denied the request for Geolocation."
                break;
            case error.POSITION_UNAVAILABLE:
                x.innerHTML = "Location information is unavailable."
                break;
            case error.TIMEOUT:
                x.innerHTML = "The request to get user location timed out."
                break;
            case error.UNKNOWN_ERROR:
                x.innerHTML = "An unknown error occurred."
                break;          
        }   
    }
</script>

How do i call getLocation() function from the component in the onNgInit method? (or can this be designed in a better way if possible?)

Final solution from accepted answer and other SO answers:

Working Code In Plunker - integrating Geolocation, angular2-google-maps and Angular2 (RC1)

Upvotes: 1

Views: 292

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657546

Add at the end of the script

window.myGetLocation = getLocation;

In the Angular component:

ngOnInit() {
  console.log(window.myGetLocation());
}

If you add

declare var navigator;

to your typescript script file you can use navigator.geolocation... inside your Angular2 component.

Plunker example

Upvotes: 1

Related Questions