NativeScript Angular - Get X and Y on tap event
Asked Answered
B

2

5

I'm doing a Nativescript-Angular-App and i have a problem.

The user has to click on the right position on a picture.

I don't understand how to get the coordinates of a simple tap.

I can get the coordinate with the touch gesture (TouchGestureEventData) but it provides a stream of informations. I just want one data.

  • GestureEventData hasn't GetX() method.
  • TouchGestureEventData has GetX() method but I want only the first touch.

I have tried with touch:

public onTouch(args: TouchGestureEventData) {
     console.log(args.getActivePointers()[0].getX());
}

But i get too many data (every movement).

Is there a way to get the coordinate just with a simple tap?

Thanks!

Bendwise answered 28/7, 2017 at 10:25 Comment(0)
R
4

If you just want to get a single touch event. what you can do is check if event action is a down action or alternatively up action. for example the below code will just get you the X and Y coordinates of the touch-down event and will only happen once for each touch event.

public onTouch(e: TouchGestureEventData) {
    if (e && e.action === 'down') {
        this.xCoord = e.getX();
        this.yCoord = e.getY();
    }
}
Referent answered 28/7, 2017 at 11:25 Comment(1)
That's working, thanks! I had found a hack (Add directly on the html invisible element with tap method) but this solution better.Bendwise
V
4

Been researching this issue, and found a way for the tap event in iOS:

onTap(e) {
    const loc = e.ios.locationInView(e.object.ios);
    console.log("(x,y) in dp: " + loc.x + "," + loc.y);
}  

I found that e.ios is the native object representation of that tap event, and tried to see what I can do with it, so I used Chrome DevTools, and started typing e.ios.location, and got the locationInView() autocomplete. I then searched for it in Apple's documentation and found that the function gets a UIView as an argument. So I tried e.ios.locationInView(e.object); and got an exception, so I remembered UIView is the iOS representation of nativescript's View class, so I tried e.ios.locationInView(e.object.ios); and got the CGPoint representing the tap coordinates in the view.
It is important to note that loc.x and loc.y are in dp units.

For Android it's a lot simpler:

onTap(e) {
    const x = e.android.getX();
    const y = e.android.getY();
    console.log("(x,y) in pixels: " + x + "," + y);
}  

Important to note that in this case the coordinates are in pixel units, so in order to convert it to dp, you would first have to import { screen } from "platform"; where your imports are, and then in order to get the x coordinate in dp, you would:
e.android.getX() / screen.mainScreen.scale

Virgy answered 24/12, 2018 at 17:19 Comment(1)
Also if you use TypeScript e should be of type TouchGestureEventData not EventData.Jocelynjocelyne

© 2022 - 2024 — McMap. All rights reserved.