1

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)

7
  • Why don't you move your code inside Angular? Commented Jun 15, 2016 at 8:46
  • The code is using the HTML geolocation API...I don't see how it can be moved inside the component... Commented Jun 15, 2016 at 8:48
  • I don't see what's the problem ;-). You can do everything inside Angular that you can do outside. Except maybe it's a timing issue that it must be done before Angular is finished loading. Commented Jun 15, 2016 at 8:49
  • You mean i can paste the getLocation function inside the component class and call it on a lifecycle hook? Commented Jun 15, 2016 at 8:51
  • Sure. Use declare to tell the TypeScript compiler it should assume the name exists (see my updated answer). Commented Jun 15, 2016 at 8:53

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.