Google disabled the ability for apps to toggle location settings a long time ago but now it's coming back with AutoTools Secure Settings.
Best of all, no root required!
First of all, check how to enable AutoTools Secure Settings here so that you can then follow this tutorial.
STEP 1 - ENABLE GPS WHILE IN GOOGLE MAPS
You can select multiple apps here if you want to turn on GPS while in other apps as well
- Add a new profile with an Application condition
- Select the Maps app
- Create the entry task
- Add an AutoTools Secure Settings action
- Set Location Mode to High Accuracy
- Accept and go back to Tasker's main screen
STEP 2 - DISABLE GPS WHEN NOT IN MAPS
- Add an exit task to the profile
- Add an AutoTools Secure Settings action
- Set Location Mode to Off
- Accept and go back to Tasker's main screen
- To make sure that the tasks are running add Flash actions to both entry and exit tasks
- Back out of Tasker to save
STEP 3 - TEST
If you now open the Google Maps app you'll see the flash and that the GPS will be first turned off and your location won't be visible. After a few seconds it'll start getting your location.
If you exit Google Maps you'll see the flash that location was turned off. You can go to your location settings to verify that the location settings were indeed changed.
Turn GPS on when in Google Maps, turn it off otherwise (No Root!)
Enable and disable location settings at will with AutoTools Secure Settings