HTML5 geolocation: logic to get initial position as well as watchLocation?
I'm using HTML geolocation and I'd like to achieve the following:
1. User arrives at page
2. User is asked to share location
3. When user says yes, Google Maps initialises and centres on their position
4. We add marker to map showing their position
5. (ongoing) As the user moves, the marker continues to move with them
I've implemented this as follows:
// Add a marker
function addMarker(loc) { // adds marker }
function setupMap(loc) { // initialise map and centre on user's position };
setUpMap(???????);
// Start watching user's position
var watchID = navigator.geolocation.watchPosition(addMarker);
So my question is: how can I get the initial position in order to set up the map?
I can see two options, both of which have flaws:
- Call
setUpMap
from withinaddMarker
, but then the map gets re-initialised each time the user moves, which is obviously inefficient. - Call
navigator.geolocation.getCurrentPosition
before callingwatchLocation
- but then the user seems to get prompted twice for their location, which looks clunky.
Any better ideas?
Thanks everyone.
UPDATE
OK, it seems I haven't explained this well. My question i开发者_开发问答s really: how do I get the user's location from watchPosition, as a one-off, so that I can initialise the map once?
Call this:
navigator.geolocation.watchPosition
instead of this:
navigator.geolocation.getCurrentPosition
watchPosition
function also initializes positions.
3. Call watchLocation in step two, i.e. to get initial location (the user therefore will only get prompted once)
精彩评论