Quick Tip - Move a Graphic
Rene Rubalcava | February 1, 2018
A quick tip today! Because someone asked me how to do this and I was like, I think I can do that.
Scenario: You're working deep cover overseas. You're cornered in an alley and have no clear eyeshot of the bad guys that are looking for you. But, you have access to a small drone in the area with a camera. You, being the geeky spy that you are have built your own web app to control the location of the drone. You need to move the location of your drone around in your mapping app so you can get a better look around to survive this harrowing ordeal!!! How would you have done that?
So I'm sure a super spy isn't writing his own drone software, but I'm sure he has someone that does...
Let's assume the basic use case of grabbing a point and moving it around. Sounds simple enough. Let's think through how you would do this for a second.
- Listen for a hold event on the map.
- Check if there is a graphic where you are holding, either a mouse pointer or touch.
- Stop the map from panning around.
- Move the graphic as you move the mouse or your finger.
- Let go of mouse or finger and stop moving the graphic and let the map pan again.
Now that we have the steps to do this task, let's look at how we can accomplish this with the JSAPI!
- Ok, so, we can listen for a hold event on the MapView. AWESOME!
- We can then use MapView.hitTest to see if there is a graphic where we touched.
- We lucked out as there is a sample showing how to disable the pan of the MapView!
- We can now use the pointer-move event to clone the Graphic, update the geometry and move the Graphic location!
- Now we can use the pointer-up event to say that we're done and clean up all the mess we made!
This is assuming you are just using points. If you are working with lines or polygons, you'll need to do some math of the vertices based on the deltas of moving the mouse around, but I'll leave that for you.
Here's a quick sample showing how you might do this with the steps above and a little flare thrown in!
Hope you enjoy the quick tip! Hack away!